本示例将会实现英文文本清洗、分词、单词去重、次数统计功能,处理大小写、标点符号等常见问题,最后输出统计结果。
示例的处理逻辑如下:
(1)文本预处理
lower():把所有单词转为小写,解决大小写不统一问题(如 Hello 和 hello 视为同一个单词)。
string.punctuation:包含所有英文标点(!@#$%^&*(),. 等),用 translate() 一次性清除所有标点。
(2)分词
split():按空格把清洗后的文本分割成纯单词列表。
(3)计数逻辑
用字典存储结果:键是单词,值是次数。
遍历单词列表,存在则计数 + 1,不存在则初始化为 1。
示例代码:
import string
def count_word_frequency(text):
"""
统计英文文本中每个单词的出现次数
:param text: 输入的英文原始文本
:return: 字典(key=单词,value=出现次数)
"""
# 1. 文本预处理:转小写 + 去除标点符号
# 转小写(统一大小写,避免 Hello 和 hello 算两个单词)
text_lower = text.lower()
# 去除所有英文标点符号
translator = str.maketrans('', '', string.punctuation)
text_clean = text_lower.translate(translator)
# 2. 分词:按空格分割成单词列表
words = text_clean.split()
# 3. 统计单词次数
word_count = {}
for word in words:
if word in word_count:
# 单词已存在,计数+1
word_count[word] += 1
else:
# 单词不存在,初始化计数为1
word_count[word] = 1
return word_count
if __name__ == "__main__":
# 测试用英文文本
sample_text = """
Hello world! Hello Python. Python is fun, fun fun!
I love Python, and I love coding.
"""
# 调用函数统计
result = count_word_frequency(sample_text)
# 打印结果
print("单词出现次数统计结果:")
for word, count in sorted(result.items()): # sorted() 按字母排序输出
print(f"{word}: {count} 次")运行结果:
单词出现次数统计结果:
and: 1 次
coding: 1 次
fun: 3 次
hello: 2 次
i: 2 次
is: 1 次
love: 2 次
python: 3 次
world: 1 次