【问题标题】:My json file can't count the tweet's words我的 json 文件无法计算推文的字数
【发布时间】:2018-02-27 16:26:23
【问题描述】:

我学习 Python 的时间很短,所以我正在通过其他人的示例进行练习。我想做推特上的词过滤,它的Python代码可以总结如下。

enter code hereimport tweepy
import simplejson as json
from imp import reload
import sys
import re

reload(sys)

consumer_key = 'blah'
consumer_skey = 'blah'
access_tokenA = 'blah'
access_stoken = 'blah'

def get_api():
 api_key = consumer_key
 api_secret = consumer_skey
 access_token = access_tokenA
 access_token_secret = access_stoken
 auth = tweepy.OAuthHandler(api_key, api_secret)
 auth.set_access_token(access_token, access_token_secret)
 return auth

class CustomStreamListener(tweepy.StreamListener):
 def __init__(self, *args, **kwargs):
    super(CustomStreamListener, self).__init__(*args, **kwargs)
    self.count = 0
    with open('C:\PYTHON\\restrictword.txt') as f:
        self.common = set(line.strip() for line in f)
    self.all_words = {}
    self.pattern = re.compile("[^\w]")
 def on_status(self, status):
    print ('I got a Tweet!')
    self.count += 1
    tweet = status.text
    words = tweet.split()
    for word in words:
        if len(word) > 2 and word != '' and word not in self.common:
            if word not in self.all_words:
                self.all_words[word] = 1
            else:
                self.all_words[word] += 1

if __name__ == '__main__':
 l = CustomStreamListener()
 try:
    auth = get_api()
    s = "Obama"
    twitterStreaming = tweepy.Stream(auth, l)
    twitterStreaming.filter(track=[s])
 except KeyboardInterrupt:
    print ('-----total tweets as follows-----')
    print (l.count)
    json_data = json.dumps(l.all_words, indent=4)
    with open('word_data.json','w') as f:
        print >> (f), json_data
        print (s)

该代码可以成功执行,因为我可以看到显示“我收到一条推文!”的控制台。根据我的python书,json file(word_data)必须算'Obamacare : 5; America : 10;'等字。但是我的json 文件是空的。我的json 文件如何计算推文的字数?

【问题讨论】:

    标签: python json twitter tweepy


    【解决方案1】:

    您没有使用 python 写入函数写入文件,而是打印它。

      with open(“hello.txt”, “w”) as f: 
      f.write(“Hello World”) 
    

    【讨论】:

    • 谢谢!我理解你的建议。但我不知道我把它们放在 f.write(??).. 我想那个 json 文件从推文中收集与“奥巴马”相关的词。
    • 我不明白你在说什么,你可以再输入一遍吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多