【问题标题】:Extracting text from a specific field in a json file in Python从Python中的json文件中的特定字段中提取文本
【发布时间】:2022-01-05 22:47:04
【问题描述】:

我的 JSON 看起来像这样(但有很多这样的行):

{"text": "Home - Homepage des Kunstvereins Pro Ars Lausitz e.V.\nKunst. Und so weiter.", "timestamp": "2018-01-20T18:56:35Z", "url": "http://proarslausitz.de/1.html"}
{"text": "Bildnummer: 79800031\nVektorgrafikSkalieren Sie ohne Aufl\u00f6sungsverlust auf jede beliebige. Ende.", "url": "http://www.shutterstock.com/de/pic.mhtml?id=79800031&src=lznayUu4-IHg9bkDAflIhg-1-15"}

我想创建一个 .txt 文件,其中仅包含来自 text 的文本。所以它只是:

Home - Homepage des Kunstvereins Pro Ars Lausitz e.V.\nKunst. Und so weiter. Bildnummer: 79800031\nVektorgrafikSkalieren Sie ohne Aufl\u00f6sungsverlust auf jede beliebige. Ende.

没有字符串,什么都没有。我认为编码(因为元音变音)之后不难解决。但是关于文本提取,我知道我可以做到:

json_object = json.loads(json_object_string)
print(json_object["text"])

但这只是为了一条线。我需要遍历这些行吗?如何将文本合并到一个 .txt 文件中?

【问题讨论】:

  • 只遍历行

标签: python json string text


【解决方案1】:
with open("file.txt", 'w') as txt_file:
    for i in range(len(js_file['...'])):
        txt_file.write(js['...'][i]['text'])

txt_file.close()

用 json 文件的主键名替换 '...'

【讨论】:

    【解决方案2】:

    我不完全确定是否有一种方法可以“矢量化”从 json 复制值,即使有,在我看来,迭代仍然可以很好地完成工作。如果我要遍历那个长 JSON 的每一行并将每个“文本”放入一个文本文件中,我会这样做:

    import json
    
    # removed escape sequences, that is not focus of problem
    test = '[{"text": "Home - Homepage des Kunstvereins Pro Ars Lausitz e.V.Kunst. Und so weiter.", "timestamp": "2018-01-20T18:56:35Z", "url": "http://proarslausitz.de/1.html"}, {"text": "Bildnummer: 79800031VektorgrafikSkalieren Sie ohne Aufl sungsverlust auf jede beliebige. Ende.", "url": "http://www.shutterstock.com/de/pic.mhtml?id=79800031&src=lznayUu4-IHg9bkDAflIhg-1-15"}]'
    
    # as you said loading the object from list of dicts into json
    test_json = json.loads(test)
    
    # opens a new text file to put the json text into
    with open("json_output.txt", 'w+') as file:
        for line in test_json:
           # assuming the text includes /n write function will paste each dict on different line
           file.write(line.get("text"))
    

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多