亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從文件夾中讀取 json 文件,獲取特定的鍵值,將鍵值寫入文件夾中的單獨文本文件

從文件夾中讀取 json 文件,獲取特定的鍵值,將鍵值寫入文件夾中的單獨文本文件

拉風的咖菲貓 2022-06-14 17:48:22
我需要在多個 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'])

就是這樣。


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號