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

Python按关键词列表拆分大文本文件的作业问题求助

问题描述

我是Python新手,作业里碰到个问题:要把有10000行的input.txt按关键词列表(Apple、Orange、Yellow)拆分成多个文件,每个关键词对应同名文件,而且只保留该关键词的第一条记录。现在的代码只支持单个关键词,不知道怎么改才能适配多关键词。

input.txt内容示例

Name: Apple
 Type: Fruits
 Description:...

 Name: Orange
 Type: Fruits
 Description:...

 Name: Yellow
 Type: Colour
 Description:...

 Name: Apple
 Type: Fruits
 Description:...

 Name: Orange
 Type: Fruits
 Description:...

 Name: Yellow
 Type: Colour
 Description:...

关键词列表

Apple
Orange
Yellow

预期输出

每个关键词对应一个同名txt文件,文件里只保留该关键词第一条记录的完整内容。

现有代码(仅支持单个关键词)

key = ['Apple']

outfile = None
fno = 0
lno = 0

with open('input.txt') as infile:
    while line := infile.readline():
        lno += 1
        if outfile is None:
            fno += 1
            outfile = open(f'{fno}.txt', 'w')
        outfile.write(line)
        
        if key in line:
            print(f'"{key}" found in line {lno}')
            outfile.close()
            outfile = None
if outfile:
    outfile.close()

修改后的代码及说明
# 定义需要处理的关键词列表
keywords = {'Apple', 'Orange', 'Yellow'}
# 记录已经处理过的关键词,避免重复写入第一条记录
processed_keys = set()
# 保存当前正在写入的文件对象和对应关键词
current_file = None
current_key = None

with open('input.txt', 'r') as infile:
    for line in infile:
        # 检查当前行是否包含未处理过的关键词
        for key in keywords:
            if key in line and key not in processed_keys:
                # 关闭之前可能打开的文件
                if current_file:
                    current_file.close()
                # 标记该关键词已处理
                processed_keys.add(key)
                # 打开对应关键词的文件准备写入
                current_file = open(f'{key}.txt', 'w')
                current_key = key
                current_file.write(line)
                break
        else:
            # 如果当前有正在写入的文件,继续写入内容
            if current_file and current_key in processed_keys:
                current_file.write(line)
                # 碰到记录之间的空行,关闭文件,结束当前记录写入
                if line.strip() == '':
                    current_file.close()
                    current_file = None
                    current_key = None

# 最后检查是否有未关闭的文件
if current_file:
    current_file.close()

关键修改点

  • 用集合存关键词和已处理记录,确保每个关键词只抓取第一条记录,避免重复操作。
  • 直接用关键词作为文件名,不再用序号命名,完全匹配需求。
  • 增加空行判断:原文件中每个记录以空行分隔,碰到空行就关闭当前文件,防止后续内容被误写入。
  • 逻辑调整:先扫每行有没有未处理的关键词,命中就开新文件写入;没命中的话,要是正在写某个文件就继续写,直到碰到分隔空行就停止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:50:00