【问题标题】:Can't get the data I want on Python无法在 Python 上获取我想要的数据
【发布时间】:2018-04-23 18:08:15
【问题描述】:

我是 Spyder 的 Python 用户。我想从记事本转换数据(推文),并将转换后的数据输出到其他记事本。它的代码是这样的。它将制作简单的数据,例如{created at: date, user_name, unicode..} -> user_name, data

try:
    import json
except ImportError:
    import simplejson as json

tweets_filename = 'C:/Users/siri_0.txt' #unconverted data
tweets_file = open(tweets_filename, "r")

for line in tweets_file:
    try:
        tweet = json.loads(line.strip())
        if 'text' in tweet: 
            print (tweet['id']) 
            print (tweet['created_at']) 
            print (tweet['text']) 
            print (tweet['user']['id']) 
            print (tweet['user']['name']) 
            print (tweet['user']['screen_name']) 
            hashtags = []
            for hashtag in tweet['entities']['hashtags']:
                hashtags.append(hashtag['text'])
            print(hashtags)

            output = "C:/Users/fn_siri.txt"
            #I want to put the converted data here.
            out_file = open(output, 'a')
            out_file.write(line)
            out_file.close()

    except:
        continue

很遗憾,C:/Users/fn_siri.txt 只能包含“未转换的数据”。如何更改包含转换后数据的代码?

【问题讨论】:

  • 您正在遍历tweets_file 中的所有line,然后执行大量printing,然后将原始line 值存储到您的输出文件中。与其将信息打印到屏幕上,不如将它们作为文本字符串存储在变量中并将它们保存到文件中。那是你需要帮助的地方吗?
  • 我解决了。谢谢:)

标签: python json twitter


【解决方案1】:
try:
    import json
except ImportError:
    import simplejson as json

tweets_filename = 'C:/Users/siri_0.txt' #unconverted data
tweets_file = open(tweets_filename, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line.strip())
        out_file = open(output, 'a')
        if 'text' in tweet: 
            print (tweet['id'],) 
            print (tweet['created_at']) 
            print (tweet['text']) 
            print (tweet['user']['id']) 
            print (tweet['user']['name']) 
            print (tweet['user']['screen_name']) 
            hashtags = []
            for hashtag in tweet['entities']['hashtags']:
                hashtags.append(hashtag['text'])
            output = "C:/Users/fn_siri.txt"
            print(hashtags,file=out_file)
            #I am assuming the converted data you want to write to out_file is hashtags
            #out_file.write(line)# why are you writing old data here ...
            out_file.close()
    except:
        continue

【讨论】:

  • 感谢您的帮助:D
【解决方案2】:

您正在将line 写入输出文件,这是您未转换的输入,而不是只写入您想要的数据。

所以,如果你想写出用户名,后跟一个逗号,然后是 e.g.文本,您需要将 out_file.write(line) 替换为:

out_file.write(tweet['user']['name'] + "," + tweet['text'] + "\n")

您需要在末尾添加\n 以确保它在每行数据之后都有一个新行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多