在多个“开始”和“结束”之间提取内容的Python代码

2024-04-27 14:41:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我绝对是python的新手。我在一个文本文件中有多篇新闻文章,有2000多个文本文件。每一篇新闻文章都以“道琼斯通讯社DJDN”开头,以“(完)道琼斯通讯社”结尾

有一组代码提取多个“开始”和“结束”之间的每个内容,如下所示:

with open('./news_txt/A_2013.txt') as infile, open('./news_txt/A_2013_a.txt', 'w') as outfile:
copy = False
for line in infile:
    if line.strip() == "Dow Jones Newswires DJDN":
        copy = True
        continue
    elif line.strip() == "(END) Dow Jones Newswires":
        copy = False
        continue
    elif copy:
        outfile.write(line)

但是,此代码仅适用于以下情况:1)只有一个txt文件;2) 所有提取的内容都存储在一个新的txt文件中

但我想要的是1)循环路径中的每个txt文件;2) 每个提取的内容都保存在一个新的txt文件中

例如,如果一个txt中有10条新闻,在运行代码后,我应该会得到10个新的txt文件来存储每条新闻

干杯


Tags: 文件代码txt内容asline文章open
2条回答
import os, os.path
folder_path = './news_txt'

def num_to_letters(n):
    rs=[]
    while n >0:
         n-=1
         n,r = divmod(n,26)
         rs.insert(0,chr(r+ord('a')))
    return ''.join(rs)

for file_name in os.listdir(folder_path):
    if not file_name.lower().endswith('.txt'):
        continue
    in_file_path = os.path.join(folder_path,file_name)
    
    
    with open(in_file_path,'r') as in_file:
        out_file = None
        num_out_files = 0
        for line in in_file:
            if line.strip() == "Dow Jones Newswires DJDN":
                if out_file is None:
                    num_out_files +=1
                    out_file_name = file_name[:-4]+'_'+num_to_letters(num_out_files)+'.txt'
                    out_file_path = os.path.join(folder_path,out_file_name)
                    out_file = open(out_file_path,'w')
                continue
            elif line.strip() == "(END) Dow Jones Newswires":
                if out_file is not None:
                    out_file.close()
                    out_file = None
                continue
            elif out_file is not None:
                out_file.write(line)
        if out_file is not None:
            out_file.close()

帮个忙,改用正则表达式:

^Dow Jones Newswires DJDN.+?^\(END\) Dow Jones Newswires

使用修饰符ms,请参见a demo on regex101.com

相关问题 更多 >