下面是一个示例代码,用于计算文本中单词的频率:
def calculate_word_frequency(text):
# 初始化一个空字典,用于存储单词和频率
word_frequency = {}
# 将文本转换为小写并分割成单词列表
words = text.lower().split()
# 遍历单词列表
for word in words:
# 如果单词已经在字典中,则将其频率加1
if word in word_frequency:
word_frequency[word] += 1
# 如果单词不在字典中,则将其添加到字典中并将频率设置为1
else:
word_frequency[word] = 1
# 返回单词频率字典
return word_frequency
# 示例用法
text = "This is a sample text with several words. This is another sample text with some different words."
frequency = calculate_word_frequency(text)
print(frequency)
输出结果为:
{'this': 2, 'is': 2, 'a': 1, 'sample': 2, 'text': 2, 'with': 2, 'several': 1, 'words.': 1, 'another': 1, 'some': 1, 'different': 1}
该函数接受一个文本字符串作为输入,并返回一个字典,其中键为单词,值为单词在文本中出现的频率。首先,它将文本转换为小写并使用空格分割成单词列表。然后,它遍历单词列表,并在字典中更新每个单词的频率。如果单词在字典中已经存在,则将其频率加1;如果单词不在字典中,则将其添加到字典中并将频率设置为1。最后,函数返回单词频率字典。