我需要在多個 json 文件中提取鍵“文本”的值,并將該值寫入 UTF-8 格式的單獨文本文件。有 2,900 個 json 文件,我已將 json、os、glob 導入運行 python 3.7 64 位、W10、VS studio 的環境,將當前工作目錄設置為存在 json 文件的文件夾python:這成功地將一個json文件'j_news1'中的關鍵'text'值寫入一個文本文件'j_news1.txt:with open('j_news1.txt', 'w') as json_file:json.dump(j_news1['text'], json_file)--我為cwd中的所有文件創建了一個文件列表:filelist = glob.glob(',/*.json')對文件夾中的所有 json 進行文件列表和打開讀取、打開寫入操作的代碼:for fname in filelist: FI = open(fname, 'r') FO = open(fname.replace('json', 'txt'), 'w') for line in FI: FO.write(line)我找不到的是如何僅提取關鍵“文本”并將其寫入單獨的文本文件。來自文件的示例 json:pprint.pprint(j_news1){'author': '', 'crawled': '2018-02-02T15:37:30.069+02:00', 'entities': {'locations': [{'name': 'us', 'sentiment': 'none'}], 'organizations': [{'name': 'mins ago cnbc', 'sentiment': 'negative'}], 'persons': [{'name': 'kate rogers', 'sentiment': 'negative'}]}, 'external_links': [], 'highlightText': '', 'highlightTitle': '', 'language': 'english', 'locations': [], 'ord_in_thread': 0, 'organizations': [], 'persons': [], 'published': '2018-02-02T14:39:00.000+02:00', 'text': "Police officer shortage growing problem in US 54 Mins Ago CNBC's " 'Kate Rogers reports police departments around the country are facing ' 'a major challenge recruiting and retaining staff.', 'thread': {'country': 'US', 'domain_rank': 767, 'main_image': 'https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2018/02/02/104984906-6ED2-SB-020218-PoliceShortage.600x400.jpg', 'participants_count': 0, 'performance_score': 0, 'published': '2018-02-02T14:39:00.000+02:00', 'replies_count': 0, 'section_title': 'Latest Video', 'site': 'cnbc.com',
1 回答

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
非常簡單:json.load(fp)會將 json 文件加載到 python 對象,然后從中提取'text'。
import json
json_object = json.load(FI)
FO.write(json_object['text'])
就是這樣。
添加回答
舉報
0/150
提交
取消