背景介绍
本项目要求开发者实现文件读取与数据统计功能,输入为多行文本,输出包含统计结果。核心实现包括:
1. 使用open()读取本地文件内容
2. 使用collections.Counter统计文本中的单词
3. 输出统计结果并保留数字格式
思路分析
- 文件读取:使用Python的
open()函数读取文本文件,确保读取完整内容。 - 数据统计:使用
collections.Counter统计文本中的单词,确保统计结果精确。 - 结果输出:根据统计结果格式化输出,确保数字保留两位小数。
代码实现
from collections import Counter
def process_text(file_path):
try:
with open(file_path, "r", encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
print("文件找不到,请检查路径是否正确。")
return {}
# 统计单词数量
word_counts = Counter(text.lower())
# 构造统计结果
result = {
"词数": len(word_counts),
"专有名词": len([word for word in word_counts if word.isalpha() and word.islower()]),
"保留数字": sum(1 for count in word_counts.values() if count.isnumeric())
}
return result
# 示例使用
if __name__ == "__main__":
result = process_text("input.txt")
print("统计结果:")
for key, value in result.items():
print(f"{key}: {value}")
总结
本项目通过Python实现文件读取与数据统计功能,展示了如何处理文本文件并统计关键统计指标。代码实现清晰,逻辑简单,可直接部署并在本地环境中运行。该项目不仅锻炼了开发者对文件处理和数据结构的理解,还提高了解决实际问题的能力。在学习过程中,需要注意异常处理和文件路径检查,确保程序的健壮性。