[英]Extracting text from a specific field in a json file in Python
我的 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"}
我想创建一个只包含 text 中的text
的.txt
文件。 所以它只是:
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
文件中?
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 文件的主键的名称
我不完全确定有一种方法可以“矢量化”从 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"))
json.load
以键/值对的形式返回数据。 通过你的 json_object data = json.load(json_object_string)
运行一个循环
为输出创建一个 .txt 文件。
output = open("newfile.txt", "a")
for e in json_object:
f.write(e['text'])
关闭你的文件
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.