我有一個 json 檔案,其中包含我使用 Twitter API 搜索的所有資料。我只想在該檔案中保留某些鍵并洗掉其余鍵,但不知道如何正確執行。我為此撰寫了一些代碼,但出現錯誤“串列索引必須是整數或切片,而不是 str”
import json
def read_json(json_file:str)->list:
tweets_data=[]
for tweet in open(json_file, 'r'):
tweets_data.append(json.loads(tweet))
return tweets_data
tags = ["created_at", "full_text"]
tweet_list=read_json('test.json')
for i in tweet_list["tweet"].keys():
if i not in tags:
del tweet_list["tweet"][i]
print (tweet_list[0])
uj5u.com熱心網友回復:
def read_json(json_file:str)->list:
tweets = []
with open(json_file, 'r') as f:
for line in f:
tweets.append(json.loads(line))
return tweets
tags = ['created_at', 'full_text']
tweets = read_json('tweets.json')
for tweet in tweets:
for key in list(tweet.keys()):
if key not in tags:
del tweet[key]
uj5u.com熱心網友回復:
您已經非常接近某些作業,但在過濾部分有一個錯誤。
您的read_json()函式回傳一個python 串列,它被分配給tweet_list.
錯誤訊息指的是tweet_list['tweet'],并表示您必須使用整數或數字對(切片)從串列中進行選擇。不是字串tweet。
如果您更改代碼以使用該號碼0
for i in tweet_list[0].keys():
if i not in tags:
del tweet_list[0][i]
它將從串列中的第一個元素中過濾掉不需要的標簽。
要過濾串列中的每個元素,您需要使用另一個 for 回圈遍歷所有元素。
for i in range(tweet_list):
for key in tweet_list[i].keys():
if key not in tags:
del tweet_list[i][key]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516868.html
