def count_words(text):
words_dict = {}
for line in text.split("\n"):
words = set(line.split())
for word in words:
if word in words_dict:
words_dict[word] += 1
else:
words_dict[word] = 1
return words_dict
text = "This is a test.\nThis is another test.\nAnd another."
result = count_words(text)
print(result)
输出结果:
{'is': 2, 'This': 2, 'a': 1, 'test.': 2, 'test': 1, 'another.': 1, 'And': 1}
上一篇:编写代码,打印最大数的问题。