首页 > 解决方案 > 如何提取文本文件中 2 个匹配项(来自 csv)之间存在的数据?

问题描述

Quetiapine fumarate Drug substance  This document
Povidone    Binder  USP
This line doesn't contain any medicine name.
Dibasic calcium phosphate dihydrate Diluent USP is not present in the csv
Lactose monohydrate Diluent USNF
Magnesium stearate  Lubricant   USNF

以上表示来自 .txt 文件的示例数据:

我有一个药物名称列表,我想在 .txt 文件中匹配它并提取 2 种药物之间存在的所有数据。(csv 文件中的药物示例是'Quetiapine fumarate', 'Povidone', 'Magnesium stearate', 'Lactose monohydrate' etc etc.)

materialcopy.csv 是包含我在下面的代码中使用的所有药物列表的文件。

我想迭代我的文本文件的每一行并创建从一种药物到另一种药物的组。

示例输出:

['Quetiapine fumarate   Drug substance  This document'],
['Povidone  Binder  USP'],
['Lactose monohydrate   Diluent USNF'],
['Magnesium stearate    Lubricant   USNF']

鉴于'Quetiapine fumarate', 'Povidone', 'Lactose monohydrate','Magnesium stearate'存在于我的 csv 物质列表中。

有人可以帮我在Python中做同样的事情吗?

尝试到现在:

import re
import pandas as pd
import csv
import os
file = open(r'C:\Users\substancecopy.csv', 'r')
oo=csv.reader(file)
allsub = []
for line in oo:
    allsub.append(line)

flat_list = [item for sublist in allsub for item in sublist]    


def extract(filename):
    file=open(filename,encoding='utf-8')
    file=file.read()

    n=[]
    for x in flat_list:
        my_regex = r"^\s?" + re.escape(x)
        #my_regex_new = r"\b" + re.escape(my_regex) + r"\b"
        if re.search(my_regex,file,flags=re.IGNORECASE|re.MULTILINE):
            n.append(x)


    n.sort()
    return n

我需要捕获从一种药物到另一种药物的所有文本,如示例输出中所示,这段代码没有发生

标签: pythonregexpython-3.xloopspattern-matching

解决方案


以下方法看起来适用于小型数据集。但是我会假设在大型数据集上它可能效率不高,并且可能有更好的方法来执行此操作。

我根据您的问题的想法采取了这种方法,所有数据都必须存储在药物名称之间。如果您只想存储匹配药物的行,您可以执行以下操作;

result = [[row.strip()] for row in data for med in meds if med in row]

#[['Quetiapine fumarate Drug substance  This document'], ['Povidone    Binder  USP'], ['Lactose monohydrate Diluent USNF'], ['Magnesium stearate  Lubricant   USNF']]

我将药物名称加载到一个列表中,您可能需要根据您的csv.

meds = ['Quetiapine fumarate', 'Povidone', 'Magnesium stearate', 'Lactose monohydrate']

with open('1.txt', 'r') as file:
    data = file.readlines()

result = [] # Empty list to store our findings

for idx, row in enumerate(data): # Get index and value of each line in the text file
    count = 0 # Set a counter for each row, this is to determine if there are no matches

    for med in meds:
        if med in row and med not in data[idx-1]: # If medication is matched and the same medication is not found in the previous row
            result.append([row.strip()])
        else: # No match found on this medication, increase counter
            count += 1

    if count == len(meds): # If count == total medication, declare no match and append to previous row
        result[-1].append(row.strip())



for i in result:
    print(i)

#['Quetiapine fumarate Drug substance  This document']
#['Povidone    Binder  USP', 'Povidone new line', "This line doesn't contain any medicine name.", 'Dibasic calcium phosphate dihydrate Diluent USP is not present in the csv']
#['Lactose monohydrate Diluent USNF']
#['Magnesium stearate  Lubricant   USNF']

我添加Povidone new line到测试文件中以证明如果在同一行中找到相同的药物名称,则会将其附加到最后一个结果中。


推荐阅读