首页 > 解决方案 > 如何将此文本转换为 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 新手

标签: 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]

推荐阅读