【问题标题】:Python Twitter json text filterPython Twitter json 文本过滤器
【发布时间】:2015-02-17 01:09:13
【问题描述】:

使用 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)

但它只返回 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_struncatedtruncatedtruncatedtruncatedtruncatedtruncatedretweeted_

在这段代码中,我如何删除某些关键字并保留主要数据“tweets”或添加它tweetStr??

【问题讨论】:

    标签: python twitter


    【解决方案1】:

    您的代码中有一个冗余循环“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)
    

    【讨论】:

    • 它仍在返回 filterKeyword :( 我应该共享我想要操作的数据文件吗?
    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2010-11-30
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多