Python实验操作题,列表,统计文件单词个数,需要详细源代码

编程实现《葛底斯堡演说》中单词的统计。 要求:1)编写函数,实现把《葛底斯堡演说》中的单词加入到列表,并统计总的单词数。 2)统计《葛底斯堡演说》到底使用了多少个不同的单词,并打印出来这些单词。

《葛底斯堡演说》是啥?

import re
text = '''
I'm asd ghj,uio asd ghj.
'''
li = re.findall(r"[A-Za-z']+", text)
print("单词列表:",li)
print("统计总的单词数:",len(li))
se = list(set(li))
print("不同的单词:",se)
print("统计不同的单词数:",len(se))

 

# coding=utf-8

def getText():
    txt = open("C:/Users/Lenovo/Desktop/1.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")
    return txt


hamletText = getText()
words = hamletText.split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
a = sum([len(line.split()) for line in open("C:/Users/Lenovo/Desktop/1.txt", 'r')])
print(a)
for i in range(a - 1):
    word, count = items[i]
    print("{0:<10}".format(word))

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632