Python文件字数日对比代码存重复值问题,求修复与优化方案
问题修复与优化方案
核心问题分析
原代码存在两个关键问题:
- 两次读取的是同一个
python_test.txt文件,没有区分昨日和今日的内容,导致统计数值完全相同 if yesterday:和if today:的判断毫无意义,因为datetime.date对象永远为真,无法起到逻辑分支作用
修复后的代码示例
方案一:按日期命名独立文件
import datetime import os def count_words_in_file(file_path): # 检查文件是否存在,不存在则返回0 if not os.path.exists(file_path): return 0 # 使用with语句自动管理文件资源 with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 分割并统计单词数量 return len(content.split()) # 获取今日和昨日日期 today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) # 生成带日期后缀的文件名 today_file = f"python_test_{today}.txt" yesterday_file = f"python_test_{yesterday}.txt" # 统计两日的单词数 today_word_count = count_words_in_file(today_file) yesterday_word_count = count_words_in_file(yesterday_file) # 对比结果并输出提示 if today_word_count > yesterday_word_count: print("Good job! You wrote a lot!") elif today_word_count < yesterday_word_count: print("You should try to keep up!") else: print("You kept the same pace today!")
方案二:用单个CSV文件记录每日数据
如果不想生成多个文件,可以用CSV统一存储每日统计结果:
import datetime import csv import os def get_daily_word_count(date): target_date = str(date) if not os.path.exists("word_counts.csv"): return 0 with open("word_counts.csv", 'r', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: if row[0] == target_date: return int(row[1]) return 0 def save_daily_word_count(date, count): # 检查文件是否存在,不存在则写入表头 file_exists = os.path.exists("word_counts.csv") with open("word_counts.csv", 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f) if not file_exists: writer.writerow(["date", "word_count"]) writer.writerow([str(date), count]) # 统计今日文件的单词数(替换为实际读取今日内容的逻辑) today = datetime.date.today() today_content = open(f"python_test_{today}.txt", 'r', encoding='utf-8').read() today_count = len(today_content.split()) save_daily_word_count(today, today_count) # 获取昨日统计数据 yesterday = today - datetime.timedelta(days=1) yesterday_count = get_daily_word_count(yesterday) # 对比输出 if today_count > yesterday_count: print("Good job! You wrote a lot!") elif today_count < yesterday_count: print("You should try to keep up!") else: print("You kept the same pace today!")
优化建议
- 更精准的单词统计:默认
split()会把带标点的内容(如"hello,")算作一个单词,可改用正则表达式re.findall(r'\w+', content)来匹配纯单词,提升统计准确性 - 异常处理增强:添加
try-except块捕获文件读取时的权限错误、编码错误等异常,避免程序崩溃 - 可配置化:将文件名前缀、存储路径等设为变量,方便后续修改
- 日志记录:增加日志功能,记录每日统计结果和对比情况,方便回溯
内容的提问来源于stack exchange,提问作者Cookie Doodle
相关产品推荐
相关产品推荐

