【发布时间】:2020-09-08 08:15:00
【问题描述】:
您好,我有一个 jsonLines 文件我试图从此处的 jsonline 文件中获取所有 Hashtags(以及应该是相同过程的提及):https://github.com/THsTestingGround/JsonL_Quest_SO/blob/master/output-2020-01-21.jsonl (所以不允许我放网址,而且有很多)
这是一个获取单个键对象的可重现示例。 我将如何继续获得多个主题标签(提及将相同)?目前我必须手动指定。无论如何要一口气把它们全部搞定? 我可以在这里使用此代码获取 csv:
import json
import csv
import io
# creates a .csv file using a Twitter .json file
# the fields have to be set manually
def extract_json(fileobj):
# Iterates over an open JSONL file and yields
# decoded lines. Closes the file once it has been
# read completely.
with fileobj:
for line in fileobj:
yield json.loads(line)
#path to the jsonl file
data_json = io.open('output-2020-01-21.json', mode='r', encoding='utf-8') # Opens in the JSONL file
data_python = extract_json(data_json)
csv_out = io.open('tweets_out_utf8.csv', mode='w', encoding='utf-8') #opens csv file
#if you're adding additional columns please don't forget to add them here
fields = u'created_at,text,full_text, screen_name,followers,friends,rt,fav' #field names
csv_out.write(fields)
csv_out.write(u'\n')
for line in data_python:
#because retweet is not common, sometimes jsonl won't have the key, so this is safer
try:
retweeted_status_full_text = '"' +line.get('retweeted_status').get('full_text').replace('"','""') + '"'
except:
retweeted_status_full_text = 'NA'
#gets me only one hastags even when there are more than one
try:
entities= '"' + line.get('entities').get('hashtags')[0].get('text').replace('"', '""') + '"'
except:
entities = 'NA'
#writes a row and gets the fields from the json object
#screen_name and followers/friends are found on the second level hence two get methods
row = [line.get('created_at'),
'"' + line.get('full_text').replace('"','""') + '"', #creates double quotes
retweeted_status_full_text,
line.get('user').get('screen_name'),
str(line.get('user').get('followers_count')),
str(line.get('user').get('friends_count')),
str(line.get('retweet_count')),
str(line.get('favorite_count'))]
row_joined = u','.join(row)
csv_out.write(row_joined)
csv_out.write(u'\n')
csv_out.close()
我确实尝试过,但它给了我一个错误。我似乎也无法在 SO 中找到解决方案。目前 json 稍弱,所以我能得到任何帮助将不胜感激。谢谢。
【问题讨论】:
-
你到底面临什么问题?
-
嗨,Sahil,我无法获取主题标签(同样,用户在“实体”键中的提及)。
line.get('entities').get('hashtags')[0].get('text')给我错误。有很多标签,想知道我是否可以将它们全部放在新列中,或者以字符串形式输入,然后我可以将其放入单个列名“Hastags” -
有很多带有空列表的标签,这就是它导致错误的原因。使用try and catch。因为您正在从空列表访问索引。
-
对不起,我可能与您沟通不畅(不是说英语的人),我可以得到单个的,但是,如果有多个标签,我将如何在不指定位置的情况下得到它们
[0]我可以以某种方式一次得到它们?
标签: python arrays json csv arraylist