python统计单词个数算法_python 统计单词个数和频次

开始学习python,习题需要统计单词个数和频次。百度找到的代码好像都有问题。自己写了一个,调试通过。

环境:python: 3.9.1 64bit ;  pycharm: 2020.2  电脑 win10  64

思路如下:

1. 打开文件,将所有字符读入list:s

2. 使用正则表达式,以非英文字符为间隔符,切片,生成一个以单词为基本元素的list

3.由于原先非字母可能连续,故生成的list可能存在空单词,所以需要去除空串

4.全部转成小写,并排序。

5. 将单词顺次存入dict,如果单词存在,则个数加一,如果不存在,则将此单词存入dict,个数设置为1

6. 输出

代码和注释如下:

import re #re模块主要功能是通过正则表达式是用来匹配处理字符串

def main(fileName):

try:

inf= open(fileName,'r')

s = inf.read()

words =re.split(r'[^a-zA-Z]',s) #以非英文字符为间隔生成list

realWords0= list(filter(None,words)) #去除空串

realWords1 =[]

for word in realWords0:

realWords1.append(word.lower()) #均转换为小写

realWords1.sort()

print("word NO: ",len(realWords1))

dict1 =dict()

for word in realWords1:

if(word in dict1): dict1[word] =dict1[word]+1

else: dict1[word]=1

for item in dict1.items():

#print(item)

print(item[0],item[1])

except IOError:

exit("That file couldn't be opened.")

return 1

main("word.txt")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值