【发布时间】:2020-07-08 18:45:01
【问题描述】:
Python3/Jupyter Notebook 问题。我有一个大的 json(> 300 万个条目)。我正在尝试将 50,000 个随机条目读入列表,并要求这些随机条目具有特定值的“country_code”参数。现在我正在阅读 300 万个条目中的每一个,缩小到具有正确国家代码的条目,然后从该子列表中获取 50,000 个随机元素。我只想阅读 50,000 条带有正确国家代码的随机行,而不必先阅读全部 300 万行。当前方法耗时太长。
我当前的代码:
def filter_json_by_country(filename, country):
file = Path(filename)
data = list()
with file.open('r') as f:
for line in f:
data.append(json.loads(line))
loc_filtered_data = []
for i in range(len(data)):
if len(data[i]['user_location']) != 0 and data[i]['user_location']['country_code'] == country:
loc_filtered_data.append(data[i])
ids = [loc_filtered_data[i]['tweet_id'] for i in range(len(loc_filtered_data))]
ids = random.sample(ids, 50000)
return ids
已编辑——json 示例:
{
"tweet_id":"1231698465102663680",
"created_at":"Sun Feb 23 21:52:52 +0000 2020",
"user_id":"433036746",
"geo_source":"tweet_text",
"user_location":{},
"geo":{},
"place":{},
"tweet_locations":
[
{
"country_code":"us",
"state":"Illinois"},
{
"country_code":"fr",
"state":"Auvergne-Rh\u00f4ne-Alpes",
"county":"Die"},
{
"country_code":"it",
"state":"Piemont",
"county":"TO",
"city":"Porte"},
{
"country_code":"fr",
"state":"Occitania",
"county":"Castres",
"city":"Lacaze"},
{
"country_code":"br",
"state":"Sergipe",
"county":"Microrregi\u00e3o do Baixo S\u00e3o Francisco Sergipano",
"city":"Propri\u00e1"}
]
}
【问题讨论】:
-
请不要标记您的 IDE 或代码编辑器,除非您的问题与编辑器本身特别相关。
-
如果您将 JSON 数据加载到 Pandas 数据框中,这可能会更有效地完成。
-
您能提供一个示例 json 吗?
-
@MZ 是的,刚刚更新
-
@MZ 他们确实提供了帮助,谢谢!! (是的,我美化了 json。)
标签: python json python-3.x dictionary