Python语言?

已知字符串变量s='''When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the Powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.''',存放了美国独立宣言中的一段话。试编写程序,实现以下功能:
(1)对文本中每个单词出现的次数进行统计,并将结果输出。
(2)输出出现次数排在前五名的单词。

s = '''When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the Powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.'''
dc = {}
ls = s.split(' ')  # 切割字符串保存到列表中
for item in ls:
dc[item] = ls.count(item)  # 统计列表中的元素出现次数,保存到字典中
sorted_dc = sorted(dc.items(), key=lambda b: b[1], reverse=True)  # 按字典的value值进行降序排序
print('前五个出现频率最高的单词:')
for item in sorted_dc[0:5]:
print(item[0], end='\t')
print('\n')
for key, value in sorted_dc[0:5].__iter__():
print('%s出现了%s次' % (key, value))

运行效果图

温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-05-08

第2个回答  2021-01-23

[吐槽大会]Python才是世界上最好的语言