Python如何按id统计字典列表中text、text_2字段的元素数与单词总数
Python实现方案
直接遍历列表中的每个字典元素分别统计即可,默认按空格拆分单词,即可匹配你要求的计数规则,可直接运行的代码如下:
def process_data(origin_list): res = [] for item in origin_list: # 统计text字段:元素个数+总单词数 text_len = len(item['text']) text_word_sum = sum(len(s.split()) for s in item['text']) # 统计text_2字段:元素个数+元组第三位文本的总单词数 text2_len = len(item['text_2']) text2_word_sum = sum(len(t[2].split()) for t in item['text_2']) # 组装结果 res.append({ 'id': item['id'], 'text': (text_len, text_word_sum), 'text_2': (text2_len, text2_word_sum) }) return res # 测试调用 myList = [ { 'id':1, 'text':[ 'I like cheese.', 'I love cheese.', 'oh!' ], 'text_2': [ ('david', 'david', 'I do not like cheese.'), ('david', 'david', 'cheese is good.') ] }, { 'id':2, 'text':[ 'I like strawberry.', 'I love strawberry' ], 'text_2':[ ('alice', 'alice', 'strawberry is good.'), ('alice', 'alice', ' strawberry is so so.') ] } ] output = process_data(myList) print(output)
输出结果
运行后得到的结果和你给出的理想输出完全一致:
[ {'id': 1, 'text': (3, 7), 'text_2': (2, 8)}, {'id': 2, 'text': (2, 6), 'text_2': (2, 7)} ]
内容的提问来源于stack exchange,提问作者Alina
相关产品推荐
相关产品推荐

