如何从多文本文件中提取特定部分

0 投票
1 回答
35 浏览
提问于 2025-04-14 16:15

我有一个包含pl编号的列表,存放在一个单独的文件里,内容如下:

Pl:105
Pl:17.3
Pl: 7.2

在一个合并的文本文件中,我有一个类似的模式:

Name :na
Pr: 78
Pl: 7.2
Unit :40
Density:80
7.3
7.8
Name :na

从一个名字到下一个名字,这个模式是一样的。

我需要把我在单独列表中的pl编号与整个名字到下一个名字之间的内容进行匹配,并把这些内容提取到不同的文本文件里。

我现在做不到,因为有将近4000个pl编号,手动去做几乎是不可能的。

1 个回答

0

我按照这些步骤操作的。第一步:从pl列表中获取所有的pl值。第二步:从合并列表中获取与pl列表中的pl值相关的值。我假设这个模式和你提供的一样。第三步:把找到的值写入以pl为名字的txt文件中。

PL_FILE = "pl_file.txt" #Which has the pl file
FULL_FILE = "full_file.txt" #Which has the merged file data

PL_LIST =[] #List that will contain all the pl values
#Loop to get all the required pl values from PL file
with open(PL_FILE) as f1:
    for line in f1:
        if ":" not in line:
            continue
        else:
           PL_LIST.append(line.split(":")[1].strip())

print("pl values found :", PL_LIST) #Gives the list of pl values

REQUIRED_PL_LIST =[]

with open(FULL_FILE) as f2:
    current_list=[]
    for line in f2:
        if "Name" in line:
            if len(current_list)>0: #has some values
                pl_val = current_list[2].split(":")[1].strip() #Gets the pl value
                if pl_val in PL_LIST:# if the pl value is in REQUIRED_PL_LIST , add it
                    REQUIRED_PL_LIST.append(current_list)
            current_list=[line] #Reset temp details
        else:
            current_list.append(line) # otherwise append

print("Associated values found for pl values : ", REQUIRED_PL_LIST)#Assoociated values obtained for pl values in pl list

#Creats text file for each pl values. and save the values. 
for list_write in REQUIRED_PL_LIST :
    file_name = list_write[2].split(":")[1].strip() +".txt"
    with open(file_name, "w") as output:
        for val in list_write:
            output.write(val)
        print("Created file " , file_name)
    

输出:

pl values found : ['105', '17.3', '7.2']
Associated values found for pl values :  [['Name :na\n', 'Pr: 78\n', 'Pl: 7.2\n', 'Unit :40\n', 'Density:80\n', '7.3\n', '7.8\n']]
Created file  7.2.txt

撰写回答