100道python基础题——(22)
题:编写一个程序来计算输入中单词的频率。 按字母顺序对键进行排序后输出。
假设为程序提供了以下输入:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
然后,输出应该是:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
提示:如果输入数据被提供给问题,则应该假定它是控制台输入。
freq = {} # frequency of words in text
print("请输入:")
line = input()
for word in line.split():
freq[word] = freq.get(word, 0) + 1 # get() 函数返回指定键的值,如果值不在字典中返回默认值。
print(freq)
words = sorted(freq.keys()) # 按key值对字典排序
for w in words:
print("%s:%d" % (w, freq[w]))
浙公网安备 33010602011771号