python - 如何将此文本转换为 json 数组格式的文本
问题描述
我有一个包含以下内容的文本文件:
{'text': 'today we will explore the culture of', 'start': 1.1, 'duration': 5.32}
{'text': 'them makkac we journey how do you say', 'start': 4.02, 'duration': 4.95}
{'text': "this one you think it's my now", 'start': 6.42, 'duration': 4.29}
{'text': "that's too long to be macaque maybe", 'start': 8.97, 'duration': 5.669}
{'text': 'Mecca Q o macaque alright Kashima island', 'start': 10.71, 'duration': 5.85}
并且需要将其转换为 json 数组。我有这个工作代码,但我有很多疑问,如果它是正确的方法来做到这一点:
if __name__ == '__main__':
s = r"""{'text': 'today we will explore the culture of', 'start': 1.1, 'duration': 5.32}
{'text': 'them makkac we journey how do you say', 'start': 4.02, 'duration': 4.95}
{'text': "this one you think it's my now", 'start': 6.42, 'duration': 4.29}
{'text': "that's too long to be macaque maybe", 'start': 8.97, 'duration': 5.669}
{'text': 'Mecca Q o macaque alright Kashima island', 'start': 10.71, 'duration': 5.85}"""
s = s.replace(r"{'text': '", r',{"text": "')
s = s.replace(r"{'text': ", r',{"text": ')
s = s.replace(r"', 'start':", r'", "start":')
s = s.replace(r"'start':", r'"start":')
s = s.replace(r"'duration':", r'"duration":')
s = '[' + s[1:] + ']'
print(s)
推荐的转换方式是什么?顺便说一下,我是 python 新手
解决方案
json 模块就是你想要的;json.loads(s)
尤其。
然而,这并不是那么简单,因为您的输入数据的 json 格式不正确。键的单引号需要是双引号,并且数组不是逗号分隔的。
下面的代码解决了这个问题
import re, json
string = r"""{'text': 'today we will explore the culture of', 'start': 1.1, 'duration': 5.32}
{'text': 'them makkac we journey how do you say', 'start': 4.02, 'duration': 4.95}
{'text': "this one you think it's my now", 'start': 6.42, 'duration': 4.29}
{'text': "that's too long to be macaque maybe", 'start': 8.97, 'duration': 5.669}
{'text': 'Mecca Q o macaque alright Kashima island', 'start': 10.71, 'duration': 5.85}"""
# regex replace single quote surround from https://stackoverflow.com/a/32529140/3959671
pattern = re.compile(r'(?:(?<!\w)\'((?:.|\n)+?\'?)(?:(?<!s)\'(?!\w)|(?<=s)\'(?!([^\']|\w\'\w)+\'(?!\w))))')
subst = u"\"\g<1>\""
result = re.sub(pattern, subst, string)
json_dict = [json.loads(x+"}") for x in result.split("}") if x]
推荐阅读
- excel - 在更多列中合并数据验证代码
- flutter - 颤振警报对话框未从函数外部更新
- angular - 角度在本地存储中的对象内添加对象
- keras - Keras:从现有神经网络创建自定义 RNN 单元
- spring-boot - 如何为自定义 UserDetails 提供用于测试安全控制器方法的附加字段?
- amazon-s3 - 使用 Informatica powercenter 在 Amazon S3 存储桶中创建文件夹模式
- ajax - 如何在 SWI Prolog 中自动下载由 Ajax 脚本生成的文件?
- cmake - CMAKE - 检查目标是否可编译
- javascript - 使用 React Hooks 在外部单击时关闭模式
- amazon-web-services - AWS Glue:更新到 2.0 并在 CloudWatch 中出现错误