可以利用Python中的字典来进行单词频率的统计。具体思路为:将输入的字符串以空格为分隔符进行拆分得到单词列表,然后遍历列表中的每个单词,将其添加到字典中作为键,如果该键已经存在,则增加键对应的值,表示该单词出现了多少次。
代码示例:
def wordFreq(inputStr):
words = inputStr.split()
freqDict = {}
for word in words:
if word in freqDict:
freqDict[word] += 1
else:
freqDict[word] = 1
return freqDict
inputStr = "hey hi Mark hi mark"
freqDict = wordFreq(inputStr)
for word, count in freqDict.items():
print(word, count)
输出结果为:
hey 1
hi 2
Mark 1
mark 1