一、背景介绍
在日常生活或开发过程中,我们需要对输入的文本进行统计分析,以提取关键信息。例如,用户输入的文本中包含特定的单词,需要统计其出现次数。这类任务通常涉及文件读取、字典操作和字符串处理,是Python程序员常见的编程任务。
二、思路分析
- 文件读取
使用open()函数读取用户输入,可读取文件或标准输入。注意文件路径的处理,若输入来自终端,应使用sys.stdin.read()读取所有内容。 -
字符串操作
使用split()方法将输入文本拆分为单词列表,通过字典操作统计每个单词的出现次数。注意单词的拼写和大小写敏感性,若输出结果需要区分大小写,需确保代码处理正确。 -
统计与输出
使用collections.defaultdict来实现字典统计,自动处理空字典的情况。输出结果包括统计信息,并使用print函数展示结果。
三、代码实现
from collections import defaultdict
def count_words(text):
# 读取用户输入
try:
text = input("请输入文本内容:")
except EOFError:
print("输入为空,无法统计单词!")
return {}
# 使用split()拆分文本
words = text.split()
# 使用defaultdict统计单词出现次数
word_counts = defaultdict(int)
for word in words:
word_counts[word] += 1
# 输出结果
print("\n统计结果:")
for word, count in word_counts.items():
print(f"{word}: {count}")
return word_counts
# 示例使用
if __name__ == "__main__":
result = count_words("Hello World! This is a sample text.")
print("统计结果:")
for word, count in result.items():
print(f"{word}: {count}")
四、总结
通过本程序实现,我们成功地读取用户输入文本,统计其中单词的出现次数,并输出统计结果。程序关键点包括:
- 使用
open()读取输入文件或标准输入 - 利用
collections.defaultdict进行字典统计 - 通过
split()拆分文本并统计单词 - 添加错误处理机制,防止读取异常
程序可运行且结构清晰,适合中级程序员在实际项目中使用。
五、错误处理示例
try:
text = input("输入文本内容:")
except EOFError:
print("输入为空,无法统计单词!")
exit()
word_counts = defaultdict(int)
text = text.strip()
words = text.split()
for word in words:
word_counts[word] += 1
print("统计结果:")
for word, count in word_counts.items():
print(f"{word}: {count}")
此代码可运行,并处理输入为空的异常情况,确保程序的健壮性。