#8.统计词频给一段文本,例如:“who have an apple apple is free free is money you know”, # 请统计单词出现的次数。 源代码如下: #创建一个列表并将文本中的单词存入其中 word_list = 'who have an apple apple is free free is money you know'.split(' ') #创建一个字典,用于存储单词以及出现次数的对应关系 word_dict = {} #遍历列表中的每一个单词 for word in word_list: if word in word_dict: #如果该单词在字典中,就让字典中存储的数字加1 word_dict[word] = word_dict[word]+1 else: #如果该单词不在字典中,就将该单词存入字典,并将出现次数初始化为1 word_dict[word] = 1 #输出统计结果 print('文本中单词以及出现的次数:') print(word_dict)
运行结果截图: