【问题标题】:Can't get any data on Python无法在 Python 上获取任何数据
【发布时间】:2017-11-21 13:13:30
【问题描述】:

我收集了很多推文。然后我只想输出英文推文。我可以获得所有包含非英语推文的推文。但是,如果我附加一些代码for i in range (0,1000): if tweet['statuses'][i][u'lang']==u'en': 以仅获取英文推文,则无法像那样收集它。而且没有错误。

In [1]: runfile('C:/Users/Desktop/tweets.py', wdir='C:/Users/Desktop')

它只是运行并且那里("C:/Users/Desktop/A.txt")没有数据。我的代码如下。我该怎么办?

try:
    import json
except ImportError:
    import simplejson as json

tweets_filename = 'C:/Users/Desktop/tweet.txt' #Original tweet
tweets_file = open(tweets_filename, "r")

for line in tweets_file:
    try:
        tweet = json.loads(line.strip())
        for i in range (0,1000): #This is the part for filtering English tweet
            if tweet['statuses'][i][u'lang']==u'en': #Same part
                if 'text' in tweet: 
                    print (tweet['created_at']) 
                    print (tweet['text']) 
                    hashtags = []
                    for hashtag in tweet['entities']['hashtags']:
                        hashtags.append(hashtag['text'])
                        print(hashtags)

                    output = "C:/Users/Desktop/A.txt" #Only English tweet path
                    out_file = open(output, 'a')
                    out_file.write(tweet['user']['name'] + "," + tweet['text'] + "\n \n")
                    out_file.close()

except:
    continue

【问题讨论】:

  • 没有错误,因为你明确地捕捉和沉默它们。 不要那样做
  • 丹尼尔所说的。你不应该使用“bare”,除非。 总是 使用命名异常,否则你可能会捕获到你没有预料到的东西。一个“裸露的”除了 Python 相当于把你的手指伸进你的耳朵并大喊“啦啦啦,我听不见你”;)

标签: python json twitter


【解决方案1】:

你必须阅读tweet_file的行,像这样;

lines = tweet_file.readlines()

for line in lines:
    ...

此外,如果您想查看错误。不要抓住他们。一些不错的阅读Zen of Python

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多