统计单词个数
【问题描述】从键盘输入英文句子,统计每个单词出现的次数。【样例输入】to be or not to be
【样例输出】to:2
be:2
or:1
not:1
s = input()
dic = {}
for i in s.split():
dic[i] = dic.get(i,0)+1
for s,n in dic.items():
print(f'{s}:{n}')
'''--result:
In: 'to be or not to be'
Out:
to:2
be:2
or:1
not:1
'''
import collections
a="to be or not to be"
lis=[i for i in a.split(" ")]
b=collections.Counter(lis)
print(b)
s = input(">>>")
d = {}
for i in s.split():
d[i] = d.get(i, 0) + 1
for i, j in sorted(d.items(), key = lambda x: x[1], reverse = True):
print(f"{i}:{j}")
def calcnt(inputstr: str):
sl = inputstr.split(' ')
dic: dict = {}
cnt = 0
for i in sl:
if dic.get(i) is not None:
dic[i] += 1
else:
cnt += 1
dic[i] = cnt
cnt = 0
for key, val in dic.items():
print(key, ":", val, "\n")
if __name__ == '__main__':
calcnt(input("输入英文句子,空格分开:"))
sentence = input("请输入需要统计的英文句子:")
for ch in ",.?!":
sentence=sentence.replace(ch, " ")
words=sentence.split()
dicts={}
for word in words:
if word in dicts:
dicts[word] += 1
else:
dicts[word]=1
items=list(dicts.items())
items.sort(key=lambda x: x[1], reverse=True)
for item in items:
word, count=item
print("{:<12}{:>5}".format(word, count))