初级Python查询选择JSON列表中的项

2024-06-26 14:10:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON twitter文件列表,我将其读入Python的列表中,如下所示:

data5=[]
with codecs.open('twitFile_5.txt','rU') as file5:
    for line in file5:
       data5.append(json.loads(line))

我可以选择“文本”例如给我一个选定的推文

data5[1]["text"]

但是我不知道怎么做

1)只需列出所有“文本”项

2)搜索“文本”列表并计算文本中提及短语列表的次数,例如[苹果]、[橘子]、[香蕉束]。你知道吗

谢谢。你知道吗


Tags: 文件文本txtjson列表asruwith
2条回答

1)使用列表

texts = [d["text"] for d in data5] 

2)再次列出理解

count = len([t for t in texts if 'apple' in t])

我把你的帖子解释为你想数一数提到“苹果”的文章的数量。如果你想数一数“苹果”出现的次数,你可以用

count = sum([t.count('apple') for t in texts])

听起来^{}^{}可以解决这些问题:

例如:

texts = map(lambda x: x['text'], data5)

以及:

texts = ['apple test', 'test orange fruit']

init = { 'apple': 0, 'orange fruit': 0, 'bunch of bananas': 0 }

def aggregate(agg,x):
  for k in agg:
    if k in x:
      agg[k] += 1
  return agg

counts = reduce(aggregate, texts, init)

编辑

每条评论:

values = [
    {'text': 'apple test', 'user': 'A'},
    {'text': 'test orange fruit', 'user': 'B'}
  ]

init = { 'apple': [], 'orange fruit': [], 'bunch of bananas': [] }

def aggregate(agg,x):
  for k in agg:
    if k in x['text']:
      agg[k].append(x)
  return agg

counts = reduce(aggregate, values, init)

相关问题 更多 >