用Python进行统计单词个数

在这里我们用字典来实现,首先读取一个文件中的字符串,去掉标点符号以及空格存到word列表中,在写入字典中根据count方法读取某个单词出现的个数。不明白这个counts方法的可以去看这篇文章https://blog.csdn.net/weixin_42800007/article/details/82024108

代码:

def create_file():
 with open("my.txt",'w') as g_file:
    g_file.write('while there is life,there is hope')
create_file()
def get_txt():
    with open("my.txt",'r') as g_file:
        str = g_file.readline()
        return str
lines = get_txt()
print(lines)
for ch in ',*.':#将字符串中的,* .替换为空格
    lines = lines.replace(ch," ")
words = lines.split()#去掉空格,将字符串中的单词提取出来

counts = {}#创建一个空的字典
for word in words:
    counts[word] = counts.get(word,0)+1
print(counts)
items = list(counts.items())#将字典中的每对键值对看做一个元素存入items列表中
items.sort(key=lambda x:x[1],reverse=True)
#根据lambda表达式来进行排序 在这里是根据数字来排序
for i in range(len(items)):
    word,count = items[i]
    print(word,count)

输出结果:

there 2
is 2
while 1
life 1
hope 1

猜你喜欢

转载自blog.csdn.net/z_xindong/article/details/87994727