Python 试图在文件中查找最常出现的名称
我有4个文本文件,我想阅读并找到最常见的5个名字。文本文件的名称格式为“Rasmus,M,11”。下面是我的代码,现在可以调用所有文本文件,然后读取它们。现在,这段代码打印出文件中的所有名称Python 试图在文件中查找最常出现的名称,python,file,python-3.x,Python,File,Python 3.x,我有4个文本文件,我想阅读并找到最常见的5个名字。文本文件的名称格式为“Rasmus,M,11”。下面是我的代码,现在可以调用所有文本文件,然后读取它们。现在,这段代码打印出文件中的所有名称 def top_male_names (): for x in range (2008, 2012): txt = "yob" + str(x) + ".txt" file_handle = open(txt, "r", encoding="utf-8")
def top_male_names ():
for x in range (2008, 2012):
txt = "yob" + str(x) + ".txt"
file_handle = open(txt, "r", encoding="utf-8")
file_handle.seek(0)
line = file_handle.readline().strip()
while line != "":
print (line)
line = file_handle.readline().strip()
top_male_names()
我的问题是,我如何跟踪所有这些名字,并找到出现最多的前五名?我能想到的唯一方法是为每个名称创建一个变量,但这行不通,因为每个文本文件中有100个条目,可能有100个不同的名称 这是它的要点:
from collections import Counter
counter = Counter()
for line in file_handle:
name, gender, age = line.split(',')
counter[name] += 1
print counter.most_common()
您可以根据自己的程序对其进行调整。如果需要计算文本中的字数,请使用正则表达式 比如说
import re
my_string = "Wow! Is this true? Really!?!? This is crazy!"
words = re.findall(r'\w+', my_string) #This finds words in the document
输出::
>>> words
['Wow', 'Is', 'this', 'true', 'Really', 'This', 'is', 'crazy']
“是”和“是”是两个不同的词。所以我们可以把所有的单词大写,然后数一数
from collections import Counter
cap_words = [word.upper() for word in words] #capitalizes all the words
word_counts = Counter(cap_words) #counts the number each time a word appears
输出:
>>> word_counts
Counter({'THIS': 2, 'IS': 2, 'CRAZY': 1, 'WOW': 1, 'TRUE': 1, 'REALLY': 1})
现在读取一个文件:
import re
from collections import Counter
with open('file.txt') as f: text = f.read()
words = re.findall(r'\w+', text )
cap_words = [word.upper() for word in words]
word_counts = Counter(cap_words)
然后,您只需对包含所有单词的dict进行排序,以获得不是键的值,并查看前5个单词。查看标准库中的
集合。Counter
。无需文件\u handle.seek(0)
。毫不害怕地删除那一行。+1代表计数器,看哪一行有一个与您试图做的几乎相同的示例。