技术背景
本项目旨在实现一个简单的文本文件处理程序。通过读取用户输入的文本文件内容,统计其中单词的出现次数,并输出统计结果。程序要求在本地环境中运行,无需依赖数据库或网络服务。采用Python语言实现,依赖基础的文件读取和数据处理功能。
思路分析
- 文件读取与处理
- 使用Python的
open()函数读取文本文件,确保文件打开时不会出现错误。 - 分割文本内容为单词,支持逐行处理。
- 使用Python的
- 单词统计与结果输出
- 使用字典统计单词出现次数,可使用
collections.defaultdict简化实现。 - 格式化输出结果,确保符合用户示例中的格式要求。
- 使用字典统计单词出现次数,可使用
实现代码
import sys
from collections import defaultdict
def read_text_file(filename):
with open(filename, 'r', encoding='utf-8') as f:
text = f.read()
return text
def count_words(text):
words = text.split()
# 使用字典统计出现次数,使用collections.defaultdict
word_counts = defaultdict(int)
for word in words:
word_counts[word] += 1
return word_counts
def main():
input_file = sys.argv[1] if len(sys.argv) > 1 else 'text.txt'
word_counts = count_words(read_text_file(input_file))
print(f"单词:{word_counts}")
if __name__ == "__main__":
main()
输出示例
输入:text.txt(内容为一段文本)
输出:
单词:{出现次数}
结束语
本项目通过文件读取和字典统计实现文本文件单词统计功能,确保输出结果符合用户示例格式要求。程序可运行在本地环境中,无需依赖数据库或网络服务。程序处理多行输入时需考虑单词分割方式,确保统计结果准确无误。