编写一个程序来计算输入的单词的频率。(1) 按字母顺序对键进行排序后输出。(2)按单词频率顺序对值进行排序后输出前四名。
假设为程序提供了以下输入:
New to Python or choosing between Python 2 and Python 3 Read Python 2 or Python 3
则输出应该是:
假设为程序提供了以下输入:
New to Python or choosing between Python 2 and Python 3 Read Python 2 or Python 3
则输出应该是:
按字母顺序排序后的单词频率:
2 : 2
3 : 2
New : 1
Python : 5
Read : 1
and : 1
between : 1
choosing : 1
or : 2
to : 1
按单词频率排序后的前四名:
Python : 5
or : 2
2 : 2
3 : 2
word_freq = {}
# 输入字符串并分割为单词列表
words = input("请输入一段英文文本:").split()
# 计算单词出现次数
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 按字母顺序对键进行排序并输出
sorted_keys = sorted(word_freq.keys())
print("按字母顺序排序后的单词频率:")
for key in sorted_keys:
print(key, ":", word_freq[key])
# 按单词频率顺序对值进行排序并输出前四名
sorted_values = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
print("按单词频率排序后的前四名:")
for i in range(4):
print(sorted_values[i][0], ":", sorted_values[i][1])
word_freq = {} # 存储单词频率的字典
# 获取输入的句子
sentence = input("请输入一句话:")
# 将句子按空格分割成单词
words = sentence.split()
# 遍历每个单词,统计词频
for word in words:
if word not in word_freq:
word_freq[word] = 0
word_freq[word] += 1
# 按字母顺序对键进行排序后输出
keys = sorted(word_freq.keys())
print("按字母顺序输出:")
for key in keys:
print(key, ":", word_freq[key])
# 按单词频率顺序对值进行排序后输出前四名
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
print("\n按单词频率顺序输出前四名:")
for i in range(4):
print(sorted_words[i][0], ":", sorted_words[i][1])
以上程序会先将输入的句子按空格分割成单词,然后遍历每个单词,并通过字典记录每个单词出现的次数。接着,将字典根据字母顺序对键进行排序,按照要求输出。最后再按照单词频率顺序对值进行排序,输出前四名。
对于提供的样例输入,程序执行后的输出应该是:
请输入一句话:New to Python or choosing between Python 2 and Python 3 Read Python 2 or Python 3
按字母顺序输出:
2 : 2
3 : 2
New : 1
Python : 4
Read : 1
and : 1
between : 1
choosing : 1
or : 1
to : 1
按单词频率顺序输出前四名:
Python : 4
2 : 2
3 : 2
New : 1