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

Python实现文本文件每行重复单词写入新文件的代码问题

修复代码:提取文件每行重复单词并写入新文件

你的代码存在两个核心问题,导致只能输出最后一行的重复单词:

  • 缩进错误:行处理逻辑(拆分单词、定义跟踪列表、内层循环)没有包含在逐行遍历的循环体内,导致代码逻辑执行异常。
  • 写入时机错误:结果写入操作放在了整个文件遍历循环的外部,仅在所有行处理完成后才写入最后一次的结果。

以下是修复后的代码:

import string 

def repeat_words(in_file, out_file):
    # 用with语句自动管理文件关闭,避免手动close的遗漏
    with open(in_file, "r") as file_in, open(out_file, "w") as file_out:
        for line in file_in:
            words = line.lower().split()
            seen_words = []
            repeat_words = [] 
            for word in words:
                # 去除单词前后的标点符号
                word = word.strip(string.punctuation)
                # 跳过空字符串(如果拆分后出现的话)
                if not word:
                    continue
                if word in seen_words and word not in repeat_words:
                    repeat_words.append(word)
                seen_words.append(word)
            # 处理完一行就写入该行的重复单词,空行则写入空行
            file_out.write(' '.join(repeat_words) + '\n')

inF = "nnn.txt"
OutF = "Untitled-1.txt"
repeat_words(inF, OutF)

额外优化点:

  • 使用with语句管理文件,无需手动调用close(),更安全且代码更简洁。
  • 添加了空字符串判断,避免处理因标点去除后产生的空内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 23:35:33