使用Python函数统计文本中单词的出现频率
发布时间:2023-07-02 12:47:35
在Python中,我们可以使用字典来统计文本中单词的出现频率。下面是一个例子:
def count_words(text):
# 创建一个空字典用于存储单词及其频率
word_count = {}
# 将文本转换为小写,并按空格分割成单词列表
words = text.lower().split()
# 遍历每个单词
for word in words:
# 去除单词中的标点符号
word = word.strip(".,!?")
# 如果单词不在字典中,则将其添加,并设置初始频率为0
if word not in word_count:
word_count[word] = 0
# 将单词的频率加1
word_count[word] += 1
return word_count
# 测试
text = "This is a sample text. It contains words, punctuations, and words again."
result = count_words(text)
print(result)
运行以上代码会输出一个字典,其中键为每个单词,值为该单词在文本中的出现频率:
{'this': 1, 'is': 1, 'a': 1, 'sample': 1, 'text': 1, 'it': 1, 'contains': 1, 'words': 2, 'punctuations': 1, 'and': 1, 'again': 1}
注意,以上代码简化了处理标点符号的步骤,实际应用中可能还需要进一步处理。同样,对于文本中存在缩写词、特殊字符等情况,还需要额外的处理。
