Python练习题15:文本词频统计:英文版哈姆雷特

文本词频统计::一篇文章,出现了哪些词?哪些词出现的最多?
‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

请统计hamlet.txt文件中出现的英文单词情况,统计并输出出现最多的10个单词,注意:‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

(1) 单词不区分大小写,即单词的大小写或组合形式一样;‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

(2) 请在文本中剔除如下特殊符号:!"#$%&()*+,-./:;<=>?@[\]^_‘{|}~‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

(3) 输出10个单词和出现次数,每个单词一行;‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

(4) 输出单词为小写形式。

def getText():
    txt = open("E:\\LX\\hamlet.txt.txt",'r').read()
    txt = txt.lower() #全部改为小写
    for ch in '!"#$%^&*()_-=+`~,./;:’[]{\|<>':
        txt = txt.replace(ch," ") #用空格代替其他字符
    return txt

hamletTxt = getText()
words = hamletTxt.split()  #split()返回一个列表
counts = {}  #字典类型
for word in words:
    counts[word] = counts.get(word,0) + 1   #如果这个单词(键)在字典中,其值+1,不在则赋以0
items = list(counts.items())  #把字典类型转换为列表类型
items.sort(key=lambda x:x[1],reverse=True)  #按多元数据的第二项(值)对列表进行排序,记!
for i in range(10):
    word,count = items[i]   #将列表中的二元数据分别赋值给word、num
    print("{0:<10}{1:>5}".format(word,count))


你可能感兴趣的:(Python,python)