【问题标题】:How to transform this text to json array formatted text如何将此文本转换为 json 数组格式的文本
【发布时间】: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


【解决方案1】:

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]

【讨论】:

    猜你喜欢
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2017-10-10
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多