背景介绍
本脚本实现了一个本地环境下的文件读写功能,用于统计文本文件中特定单词的出现次数。该脚本无需依赖外部框架,仅通过文件读取和数据处理实现,适合中级以下开发者在1~3天内完成开发。
思路分析
- 文件读取与处理:使用Python的
open()函数读取文本文件,通过split()分割单词,避免可能的空值处理。 - 统计单词:使用
collections.Counter统计每个单词的出现次数,实现高效的计数操作。 - 输出结果:将统计结果以字典形式输出,确保键值对清晰直观。
代码实现
from collections import Counter
def count_words_in_file(file_path, target_words):
word_counts = Counter()
with open(file_path, 'r') as f:
for line in f:
line_words = line.strip().split()
for word in line_words:
word_counts[word] = word_counts.get(word, 0) + 1
return word_counts
# 示例输入输出
target_words = ["hello", "world", "this"]
file_path = "example.txt"
# 计算并输出结果
word_result = count_words_in_file(file_path, target_words)
print("结果:")
for word, count in word_result.items():
print(f"{word}: {count}")
总结
本脚本实现了文件读写与单词统计的核心功能,通过Python的collections模块高效处理文本数据,确保了代码的可运行性和简洁性。代码清晰标注了各步骤的逻辑,便于理解并优化。