python 下载纯英文书籍,计算出现的单词数和每个单词的次数,统书中使用频率最高最低的20单词?

python编程 下载无版权纯英文文本文档书籍,去计算书中出现的单词总数,以及每个单词的次数,统计书中使用频率最高和最低的20个单词是什么? 求大佬解答

sentence = 'hello world nihao world hey hello java world hi python yeoman word'

#先把字符串分割成单个单词列表
list1 = sentence.split()
#['hello', 'world', 'nihao', 'world', 'hey', 'hello', 'java', 'world', 'hi', 'python', 'yeoman', 'word']
print list1

#把列表转为结合,为了去除重复的项
set1 = set(list1)
#set(['java', 'python', 'word', 'nihao', 'hey', 'yeoman', 'hi', 'world', 'hello'])
print set1

#把集合转为列表,集合元素没有顺序,没有索引属性,而列表有
list2 = list(set1)
#['java', 'python', 'word', 'nihao', 'hey', 'yeoman', 'hi', 'world', 'hello']
print list2

#新建一个空的字典
dir1 = {}

for x in range(len(list2)):
dir1[list2[x]] = 0 #字典值初始为0
for y in range(len(list1)):
if list2[x] == list1[y]:
dir1[list2[x]] += 1

#{'word': 1, 'python': 1, 'nihao': 1, 'hey': 1, 'hello': 2, 'hi': 1, 'world': 3, 'java': 1, 'yeoman': 1}
print dir1
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-11-23
fhv the one that has been published by my phone and I'm not going on with my friends with me
第2个回答  2020-11-24

可以用collections库中的Counter进行统计。


from collections import Counter

txt='hello world nihao world hey hello java world hi python yeoman word'

print('频率最高:',Counter(txt.split()).most_common(4))

print('频率最低:',sorted(Counter(txt.split()).most_common(),key=lambda x:x[1],reverse=False)[:4])

第3个回答  2020-11-23
是作业吧 简单追问

对 大佬能解答一下吗

追答

可以 私信帮

第4个回答  2020-11-23
fhv the one that has been published by my phone and I'm not going on with my friends with me
第5个回答  2020-11-24

可以用collections库中的Counter进行统计。


from collections import Counter

txt='hello world nihao world hey hello java world hi python yeoman word'

print('频率最高:',Counter(txt.split()).most_common(4))

print('频率最低:',sorted(Counter(txt.split()).most_common(),key=lambda x:x[1],reverse=False)[:4])

第6个回答  2020-11-23
是作业吧 简单追问

对 大佬能解答一下吗

追答

可以 私信帮

相似回答