You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取文本文件统计指定单词并输出对应时间

修正代码实现指定单词统计与对应区块日期输出

原代码问题分析

  • 未读取文件内容就调用data.count,data变量未定义,直接运行会报错
  • 循环内将文件对象f重定义为字符串,破坏了文件迭代器,导致后续循环无法正常执行
  • 没有跟踪每个文本区块的顶部日期,盲目输出所有行的前19字符,完全不符合需求

修正后的代码

target_word = "specific word"
occurrences = 0
block_dates = set()  # 用集合避免同一区块多次出现目标单词时重复输出日期
current_date = ""

with open('file_name.txt', 'r') as f:
    for line in f:
        stripped_line = line.strip()
        # 判断当前行是否为区块顶部的日期行(匹配YYYY-MM-DDTHH:MM:SSZ格式特征)
        if len(stripped_line) >= 20 and stripped_line[19] == 'Z' and stripped_line[10] == 'T':
            # 提取前19位,去掉末尾的Z,得到目标格式的日期
            current_date = stripped_line[:19]
        # 检查当前行是否包含目标单词(兼容示例中的**标记包裹场景)
        if target_word in line:
            occurrences += 1
            if current_date:
                block_dates.add(current_date)

# 输出最终结果
print(f'Number of occurrences of the word : {occurrences}')
for date in sorted(block_dates):
    print(date)

代码逻辑说明

  • 使用with语句自动管理文件资源,无需手动关闭文件,避免资源泄漏
  • 用block_dates集合存储出现目标单词的区块日期,确保同一区块多次出现目标单词时只输出一次日期
  • 通过格式特征(长度、T和Z的位置)精准识别区块顶部的日期行
  • 逐行统计目标单词的总出现次数,同时收集对应的区块日期
  • 最后按日期顺序输出结果,保证与示例输出逻辑一致

测试结果

用你提供的示例文本测试,输出将与期望完全一致:

Number of occurrences of the word : 2
2023-09-15T16:55:10
2023-09-15T16:57:30

内容的提问来源于stack exchange,提问作者user22564304

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:20:18