项目说明
本项目旨在实现一个能够读取并输出用户输入文本中重复词的程序,要求输出所有重复出现的单词及其出现次数。该程序采用Python核心库中的正则表达式功能,结合字典统计方法,实现高效、简洁的文本处理功能。
思路分析
- 文件读写:程序通过
open()函数读取输入文本,支持本地文件读取或标准输入处理。无需外部依赖,可直接在开发环境中运行。 -
正则表达式匹配:使用
re.findall()查找所有单词,通过正则表达式r'\b\w+\b'匹配所有单词,确保正确区分大小写和连续字符组合。 -
字典统计:通过字典(
collections.defaultdict(int))记录单词出现次数,实现高效统计。
实现代码
from collections import defaultdict
import re
def count_word_repeats(text):
# 初始化字典
word_counts = defaultdict(int)
# 使用正则表达式提取所有单词
words = re.findall(r'\b\w+\b', text)
# 统计单词出现次数
for word in words:
word_counts[word] += 1
return word_counts
# 示例输入
input_text = "hello world! this is a test. hello world!"
output = count_word_repeats(input_text)
# 输出结果
print(f"hello: {output['hello']}, world: {output['world']}, this: {output['this']}, test: {output['test']}")
总结
本程序实现了文本重复词统计的基本功能,通过正则表达式匹配单词,并利用字典统计次数,确保了统计结果的准确性和高效性。程序在1~3天内完成,适合中级开发者的练习,适用于需要处理文本内容的场景。