我有一个任务,我必须创建一个带有函数列表的模块,其中一个字符串被写入到文件中。我遇到的问题是,我必须计算一个单词在输入字符串中出现的次数,并将其添加到字典中。字典的关键字将是单词,值将是单词在字符串中出现的次数。
def word_freq_dict(): # function to count the amount of times a word is in the input string
file = open("data_file.txt", 'r')
readFile = file.read() #reads file
words = readFile.split() #splits string into words, puts each word as an element in a list其他的函数都能用,我已经确定了。到目前为止,我所做的是将这些单词放入一个列表中。我想将每个单词在列表中出现的次数相加,并将其添加到字典中,其中单词是关键字,出现次数是值。此函数不返回任何内容。
发布于 2016-10-25 08:57:38
有一种非常简单的方法可以做到:
word_count = {}
for word in words:
word_count[word] = word_count.get(word,0) + 1通过在dict.get()函数中使用0作为默认值,它会在单词第一次出现时返回0。如果该单词已在字典中,则返回该键的当前值。然后,您只需在每次迭代中添加1。
https://stackoverflow.com/questions/40229618
复制相似问题