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

问题描述 投票:0回答:1

我有订单号清单。在单独的文件中,如下所示:

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 编号,并仅将整个名称中的 PL 号提取到下一个名称到不同的不同文本文件。

我无法做到这一点,因为有近 4000 个 PL ID,手动执行此操作几乎是不可能的。

python ubuntu
1个回答
0
投票

我按照以下步骤操作。 1)从 pl 列表中获取所有 pl 值 2)获取合并列表中与 pl 列表中的 pl 值关联的值。我认为该模式与您提供的相同。 3)将找到的值写入到以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
© www.soinside.com 2019 - 2024. All rights reserved.