参考下面实现代码:
def mydic(words):
wordList = {}
for index in words:
try:
wordList[index] += 1
except KeyError:
wordList[index] = 1
return wordList
words = "hi,hi,u,hello,单词,hello,单词,单词,hi"\nwlists = words.split(',')
print(wlists)
print(mydic(wlists))
运行结果如下:
['hi', 'hi', 'u', 'hello', '单词', 'hello', '单词', '单词', 'hi']
{'hi': 3, 'u': 1, 'hello': 2, '单词': 3}