【问题标题】:How to read twitter-json file and save it as a csv with Python如何使用 Python 读取 twitter-json 文件并将其保存为 csv
【发布时间】:2015-11-12 10:23:38
【问题描述】:

我有a json-text file containing tweets from a certain hashtag。现在我将它转换为一个矩阵,每条推文都有一行,还有一个列数组,如用户、时间、纬度、经度等。我已经编写了以下代码,但是当我得到输出文件时,信息没有保存。它刚刚显示了标题行:

#import module
import json
from csv import writer

#input file
tweets = ()
for line in open('file.txt'):
    try: 
        tweets.append(json.loads(line))
    except:
        pass

#variables
ids = [tweet['id_str'] for tweet in tweets]
times = [tweet['created_at'] for tweet in tweets]
users = [tweet['user']['name'] for tweet in tweets]
texts = [tweet['text'] for tweet in tweets]
lats = [(T['geo']['coordinates'][0] if T['geo'] else None) for T in tweets]
lons = [(T['geo']['coordinates'][1] if T['geo'] else None) for T in tweets]
place_names = [(T['place']['full_name'] if T['place'] else None) for T in tweets]
place_types = [(T['place']['place_type'] if T['place'] else None) for T in tweets]

#output file
out = open('tweets_file.csv', 'w')
print >> out, 'id,created,text,user,lat,lon,place name,place type'
rows = zip(ids, times, texts, users, lats, lons, place_names, place_types)
csv = writer(out)
for row in rows:
    values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
    csv.writerow(values)
out.close()

请您帮我找到并清除错误...在此先感谢。

R.

【问题讨论】:

  • SO no es un servicio de revisión de código。 Tu programa falla en varios sitios con errores en tiempo de ejecución。 Es mejor mostrar respeto por el tiempo de la gente que te puede ayudar de manera gratuita y desinteresada。 Antes de postear una pregunta debes isolar el problema y preguntar por lo que falla: no es correcto vomitar todo el codigo y todos los datos y decir "no funcioina"。 Te envío un enlace que habla sobre este tema:stackoverflow.com/help/mcveSuerte con tu estudio de twitter。
  • ¡ 非常感谢! Tranquilo tienes toda la razón en que tengo que ser mucho más específico。 Y aunque llevo un tiempecillo por aquí,没有大豆程序员,aunque intento aprender a serlo。

标签: python json csv twitter


【解决方案1】:

在您的代码中,tweets 是 tuple:

'tuple' 对象没有属性'append'

您似乎从多个来源复制粘贴代码,但不了解在做什么。

import json
from csv import writer

with open('file.txt') as data_file:    
    data = json.load(data_file)

tweets = data['statuses']

ids = [tweet['id_str'] for tweet in tweets]
times = [tweet['created_at'] for tweet in tweets]
...

【讨论】:

  • 是的,你是对的。一开始的推文是一个列表,然后我改变了它以寻找错误。但正如你所见,我没有。
  • ¡¡¡亲切!!!米尔格拉西亚斯。 Así que el questiona residía en cómo abrir el archivo y no en la declaración de variables...
猜你喜欢
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2017-05-02
  • 2019-08-23
  • 1970-01-01
  • 2021-06-11
  • 2017-11-02
  • 1970-01-01
相关资源
最近更新 更多