【文本文件单词数统计】统计《哈姆雷特》作品文本文件中除一些冠词、代词、连接词之外出现最多的单词,打印数量最多的前十个单词

统计是计算科学、管理学、社会学、数学等诸多领域的基本问题,相关问题、方法和技术组成了一门学科,即“统计学”

问题描述如下:

利用python程序统计《哈姆雷特》作品中出现最多的单词,设置排除词库,排除一些冠词、代词、连接词等。

Hamlet全集文本文件部分内容如下:

如有需要可联系博主获取Hamlet全集文本文件。

程序代码如下:

excludes = {"the", "and","to","that","his","this","but","of", "you",
            "a", "an","i","we","it", "my","me", "in","your","he"}#排除词库
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")  # 将文本中特殊字符替换为空格
    return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
for word in excludes:
    del (counts[word])
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
print("Hamlet出现最多的的单词为:")
for i in range(10):
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

程序运行结果如下:

 看到这里的小伙伴别忘了点个赞再走哦!

关注博主学习更多Python程序设计知识! 

猜你喜欢

转载自blog.csdn.net/qq_59049513/article/details/122582729