没有合适的资源?快使用搜索试试~ 我知道了~
首页Python统计纯文本文件中英文单词出现个数的方法总结【测试可用】
资源详情
资源评论
资源推荐

Python统计纯文本文件中英文单词出现个数的方法总结【测试统计纯文本文件中英文单词出现个数的方法总结【测试
可用】可用】
主要介绍了Python统计纯文本文件中英文单词出现个数的方法,结合实例形式总结分析了Python针对文本文件的
读取,以及统计文本文件中英文单词个数的4种常用操作技巧,需要的朋友可以参考下
本文实例讲述了Python统计纯文本文件中英文单词出现个数的方法。分享给大家供大家参考,具体如下:
第一版第一版: 效率低
# -*- coding:utf-8 -*-
#!python3
path = 'test.txt'
with open(path,encoding='utf-8',newline='') as f:
word = []
words_dict= {}
for letter in f.read():
if letter.isalnum():
word.append(letter)
elif letter.isspace(): #空白字符 空格
if word:
word = ''.join(word).lower() #转小写
if word not in words_dict:
words_dict[word] = 1
else:
words_dict[word] += 1
word = []
#处理最后一个单词
if word:
word = ''.join(word).lower() # 转小写
if word not in words_dict:
words_dict[word] = 1
else:
words_dict[word] += 1
word = []
for k,v in words_dict.items():
print(k,v)
运行结果:
we 4
are 1
busy 1
all 1
day 1
like 1
swarms 1
of 6
flies 1
without 1
souls 1
noisy 1
restless 1
unable 1
to 1
hear 1
the 7
voices 1
soul 1
as 1
time 1
goes 1
by 1
childhood 1
away 2
grew 1
up 1
years 1
a 1
lot 1
















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0