所以我有一個帶有這個 reddit 評論的 txt 文件:dict 的每一行都有很多信息,我只想要那里的 2 個元素,即author和body。我正在嘗試遍歷文件的每一行,以刪除不必要的信息并僅保留這兩個信息。我搜索了很多,但沒有找到任何對我有幫助的東西。輸出應該是一個新的 filename.txt,每行的字典中只有作者和正文。我只是意識到它是json格式的。所以我嘗試了這個:問題是,現在當我刪除不必要的元素時,它也刪除了它的價值。 listcomments = [] for line in open ('RC_2009-01.json', 'r'): listcomments.append(json.loads(line)) #res = dict([(key, val) for key, val in comments.items() if key not in rem_list]) #print(res) for line in listcomments: rem_list = ['subreddit_id', 'name', 'author_flair_text', 'link_id', 'score_hidden', 'retrieved_on', 'controversiality', 'parent_id', 'subreddit', 'author_flair_css_class', 'created_utc', 'gilded', 'archived', 'distinguished', 'id', 'edited', 'score', 'downs', 'ups'] list1 = [ele for ele in line if ele not in rem_list] out_file = open("teste2.json", "w") json.dump(list1, out_file, indent = 4)
2 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
你來做這件事。
假設你有一本像下面這樣的字典。
a={chr(i):j for i,j in zip(range(65,91),range(1,27))}
'''a={'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9,
'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18,
'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26}'''
并且您只想提取'A'and 'C'。
wanted_key=['A','C']
res={key:a.get(key) for key in wanted_key}
print(res)
輸出
{'A': 1, 'C': 3}

喵喔喔
TA貢獻1735條經驗 獲得超5個贊
添加回答
舉報
0/150
提交
取消