使用Python从Twitter JSON数据中解析“用户”数据

时间:2014-04-23 20:32:35

标签: python json twitter

我尝试使用Python解析一些Twitter数据,以便在“用户”中提取信息。推文领域。下面是我的代码,以及我不断得到的错误。我的目标是打印出screen_name,关注者数量,数据集中每行的朋友数量。我确信这对我来说是一个简单的问题,但任何帮助都非常感谢。

导入json import sys

def main():


    for line in sys.stdin:
        line = line.strip()

        data = ''

        try:
            data = json.loads(line)
        except ValueError as detail:
           continue

        if not (isinstance(data, dict)):
            ## not a dictionary, skip
            pass
        elif 'delete' in data:
            ## a delete element, skip for now.
            pass
        elif 'user' not in data:
            ## bizarre userless edge case
            pass
        else:
            print "\t".join([
            data['user']['screen_name'],
            data['user']['followers_count'], 
            data['user']['friends_count']
            ])

if __name__ == '__main__':
    main()

错误:

Traceback (most recent call last):
  File "/home/titan/print_info_FAST.py", line 33, in <module>
    main()
File "/home/titan/print_info_FAST.py", line 29, in main
  data['user']['friends_count']
TypeError: sequence item 1: expected string or Unicode, int found    

1 个答案:

答案 0 :(得分:0)

join方法需要一个字符串列表,但是你的列表包含整数,你需要将整数解析为字符串,试试这个:

print "\t".join([
data['user']['screen_name'],
str(data['user']['followers_count']), 
str(data['user']['friends_count'])
])