gpt4 book ai didi

python - 我的 json 文件无法计算推文的字数

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:05 26 4
gpt4 key购买 nike

我学习Python的时间很短,所以我正在通过其他人的示例进行练习。我想做Twitter上的文字过滤,其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;之类的单词。美国:10;'。但我的 json 文件是空的。我的 json 文件如何计算推文的字数?

最佳答案

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

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

关于python - 我的 json 文件无法计算推文的字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46291054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com