从lis中提取频率

2024-04-26 13:21:10 发布

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

我使用Counter对列表进行排序,并尝试从排序的列表中提取频率。我该怎么做才能得到2022和1393这样的数字来做一些计算呢?你知道吗

from collections import Counter
title_file = open("title.txt", "r")

headers = title_file.readline()
titles = []

for line in title_file.readlines():
  line.rstrip()
  (name, title) = line.split('\t')
  titles.append(title)

titlecount = Counter(titles).most_common()
print "%s" % (titlecount)
#sample output: [('PROFESSOR', 2022), ('REGISTERED NURSE - LEVEL B', 1393)]

Tags: fromimporttxt列表排序titlelinecounter
1条回答
网友
1楼 · 发布于 2024-04-26 13:21:10

从counter得到的列表是一个元组列表。第一个元素是令牌的名称,第二个元素是其出现次数的计数。你知道吗

只需在列表中循环:

title_count = Counter(titles).most_common()
for name,count in title_count:
    print('{} was found {} times'.format(name, count))

相关问题 更多 >