Python 推特 json 文本过滤器
Python Twitter json text filter
使用来自 Twitter 的流 API,我可以获得 JSON 格式的数据。
但是,我很难使用 python 从数据集中过滤掉某些关键字。以下是我所做的。
首先我定义了空字符串和过滤列表:
tweets=[]
tweetStr=''
tweetsFiltered=[]
然后我所做的是打开 json 文件,将其附加到 tweets=[] 以下:
for line in open('apple.json'):
try:
tweets.append(json.loads(line))
except:
pass
然后对于tweet数据,我希望过滤掉关键字并擦除
filterKeyword=['eat','cinnamon','fruit','pie','juice']
for tweet in tweets:
for tweet['text'] in tweet:
for key in filterKeyword:
if key in tweet['text']:
pass
else:
tweetsFiltered.append(tweet)
tweetStr+=str(tweet['text'])
print(tweetStr)
但它 returns 我只有 JSON 文件中的键(我认为它是字典键)像这样
timestamp_mstimestamp_mstimestamp_mstimestamp_mstimestamp_msretweetedretweetedretweetedretweetedretweetedin_reply_to_user_id_strin_reply_to_user_id_strin_reply_to_user_id_strin_reply_to_user_id_strin_reply_to_user_id_strtruncatedtruncatedtruncatedtruncatedtruncatedretweeted_statusretweeted_status
在这段代码中,如何删除某些关键字并保留主要数据"tweets"或添加它tweetStr??
您的代码中有一个冗余循环"for tweet['text'] in tweet"。
这是正确的代码:
filterKeyword=['eat','cinnamon','fruit','pie','juice']
for tweet in tweets:
for key in filterKeyword:
if key in tweet['text']:
pass
else:
tweetsFiltered.append(tweet)
tweetStr+=str(tweet['text'])
print(tweetStr)
使用来自 Twitter 的流 API,我可以获得 JSON 格式的数据。 但是,我很难使用 python 从数据集中过滤掉某些关键字。以下是我所做的。
首先我定义了空字符串和过滤列表:
tweets=[]
tweetStr=''
tweetsFiltered=[]
然后我所做的是打开 json 文件,将其附加到 tweets=[] 以下:
for line in open('apple.json'):
try:
tweets.append(json.loads(line))
except:
pass
然后对于tweet数据,我希望过滤掉关键字并擦除
filterKeyword=['eat','cinnamon','fruit','pie','juice']
for tweet in tweets:
for tweet['text'] in tweet:
for key in filterKeyword:
if key in tweet['text']:
pass
else:
tweetsFiltered.append(tweet)
tweetStr+=str(tweet['text'])
print(tweetStr)
但它 returns 我只有 JSON 文件中的键(我认为它是字典键)像这样
timestamp_mstimestamp_mstimestamp_mstimestamp_mstimestamp_msretweetedretweetedretweetedretweetedretweetedin_reply_to_user_id_strin_reply_to_user_id_strin_reply_to_user_id_strin_reply_to_user_id_strin_reply_to_user_id_strtruncatedtruncatedtruncatedtruncatedtruncatedretweeted_statusretweeted_status
在这段代码中,如何删除某些关键字并保留主要数据"tweets"或添加它tweetStr??
您的代码中有一个冗余循环"for tweet['text'] in tweet"。 这是正确的代码:
filterKeyword=['eat','cinnamon','fruit','pie','juice']
for tweet in tweets:
for key in filterKeyword:
if key in tweet['text']:
pass
else:
tweetsFiltered.append(tweet)
tweetStr+=str(tweet['text'])
print(tweetStr)