从键盘输入一个英文句子或单词组成的字符串,可以不包含标点符号,但单词之间要用空格分开。将句子中单词及出现的频次分别作为key和value保存在字典中,并输出。(提示:字符串的split方法可以将字符串转成列表,列表的count方法可以统计列表元素的频次。)
示例代码如下:
sentence = input("请输入英文句子或单词组成的字符串: ")
words = sentence.split()
word_freq = {}
for word in words:
word_freq[word] = words.count(word)
print("单词及其频次:")
for word, freq in word_freq.items():
print(word, ":", freq)
代码实现:
sentence = input()
words_list = sentence.split() # 将字符串转成列表
words_dict = {} # 创建空字典
for word in words_list:
words_dict[word] = words_list.count(word) # 统计单词出现的频次,保存在字典中
for key, value in words_dict.items(): # 遍历字典,输出单词及其频次
print(key, value)
执行结果: