【发布时间】:2021-07-02 21:30:29
【问题描述】:
我有一个包含以下内容的文本文件:
{'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 新手
【问题讨论】:
-
有python的json模块
标签: python