当前位置:首页>python>python高阶:30、英文词频统计

python高阶:30、英文词频统计

  • 2026-10-11 06:07:57
python高阶:30、英文词频统计
1、hamlet.txt文本文件下载:

通过网盘分享的文件:hamlet.txt

链接: https://pan.baidu.com/s/14ub6O90xKNpo19p2VP0ZHA?pwd=dkzx 提取码: dkzx

2、英文词频统计
  (1)读取文件:open()函数
f=open("hamlet.txt","r")  #创建文件操作对象fprint(f)txt=f.read()   #调用read方法读取文本内容,返回字符串print(txt)
(2)字符方法处理:将文本中的大写字母转换为小写,去除标点符号,并按空格拆分字符串
f=open("hamlet.txt","r")  #创建文件操作对象fprint(f)txt=f.read()    #调用read方法读取文本内容,返回字符串print(txt)txt=txt.lower() #将字符中的大写字母转换为小写print(txt)for i in "~!@#$%^&*()_+<>?:\"{}|[]\;\',./\\'-":    txt=txt.replace(i," ")   #用空格替换字符串中标点符号lst=txt.split()  #默认按空格分隔字符串,返回列表print(lst)
(3)统计单词出现的次数:遍历列表,添加到字典中
f=open("hamlet.txt","r")  #创建文件操作对象fprint(f)txt=f.read()    #调用read方法读取文本内容,返回字符串print(txt)txt=txt.lower() #将字符中的大写字母转换为小写print(txt)for i in "~!@#$%^&*()_+<>?:\"{}|[]\;\',./\\'-":    txt=txt.replace(i," ")   #用空格替换字符串中标点符号lst=txt.split()  #默认按空格分隔字符串,返回列表print(lst)counts={}    #空字典for word in lst:    counts[word]=counts.get(word,0)+1  #单词出现一次,数量加1print(counts)items=list(counts.items())  #将字典中的键值对转换为元组,并以列表形式返回print(items)
(4)利用lambda匿名函数对单词数量进行从大到小排序,并遍历排序后的前10个元素
f=open("hamlet.txt","r")  #创建文件操作对象fprint(f)txt=f.read()    #调用read方法读取文本内容,返回字符串print(txt)txt=txt.lower() #将字符中的大写字母转换为小写print(txt)for i in "~!@#$%^&*()_+<>?:\"{}|[]\;\',./\\'-":    txt=txt.replace(i," ")   #用空格替换字符串中标点符号lst=txt.split()  #默认按空格分隔字符串,返回列表print(lst)counts={}    #空字典for word in lst:    counts[word]=counts.get(word,0)+1  #单词出现一次,数量加1print(counts)items=list(counts.items())  #将字典中的键值对转换为元组,并以列表形式返回print(items)items.sort(key=lambda x:x[1],reverse=True)   #按单词出现次数排序print(items)for i in range(10):    word,count=items[i] #序列解包    print(f"{word:<10}{count:>5}")   #格式化输出

最新文章

随机文章