Regex 解析目录中包含一组字符串匹配项的文件-使用“匹配到新文件”命令行

Regex 解析目录中包含一组字符串匹配项的文件-使用“匹配到新文件”命令行,regex,python-3.x,set,python-requests,glob,Regex,Python 3.x,Set,Python Requests,Glob,我需要解析一个包含多个excel文件的目录,以找到与一组500多个字符串(我目前在一组中)的匹配项 如果与excel文件中的一个字符串匹配,我需要将该行拖出到一个新文件中 如果你能帮忙,请告诉我提前感谢您的帮助 该目录名为:All_Data 该集合来自文件中的字符串列表(MRN_file_path) 我的代码: MRN = set() with open(MRN_file_path) as MRN_file: for line in MRN_file: if line.s

我需要解析一个包含多个excel文件的目录,以找到与一组500多个字符串(我目前在一组中)的匹配项

如果与excel文件中的一个字符串匹配,我需要将该行拖出到一个新文件中

如果你能帮忙,请告诉我提前感谢您的帮助

该目录名为:All_Data

该集合来自文件中的字符串列表(MRN_file_path)

我的代码:

MRN = set()
with open(MRN_file_path) as MRN_file:
    for line in MRN_file:
        if line.strip():
            MRN.add(line.strip())

for root, dires, files in os.walk('path/All_Data'):
    for name in files:
        if name.endswith('.xlsx'):
            filepath = os.path.join(root, name)
            with open(search_results_path, "w") as search_results:
                if MRN in filepath:
                    search_results.write(line)

您的代码实际上并不读取.xlsx文件。据我所知,本机Python中没有任何东西可以读取.xlsx文件。不过,您可以检查一下,看看这是否有帮助。下面是一个解决方案,它读取指定目录中的所有.xlsx文件,并将它们写入一个以制表符分隔的txt文件

import os
from openpyxl import load_workbook

MRN = set()
with open(MRN_file_path) as MRN_file:
    for line in MRN_file:
        if line.strip():
            MRN.add(line.strip())

outfile = open(search_results_path, "w")

for root, dires, files in os.walk(path):
    for name in files:
        if name.endswith('.xlsx'):
            filepath = os.path.join(root, name)
            # load in the .xlsx workbook
            wb = load_workbook(filename = filepath, read_only = True)
            # assuming we select the worksheet which is active
            ws = wb.active
            # iterate through each row in the worksheet
            for row in ws.rows:
                # iterate over each cell
                for cell in row:
                    if cell.value in MRN:
                        # create a temporary array with all the cell values in the matching row.
                        # the 'None' check is there to avoid errors when joining the array
                        # into a tab-delimited row
                        arr = [cell.value if cell.value is not None else "" for cell in row]
                        outfile.write("\t".join(arr) + "\n")
outfile.close()

如果以制表符分隔的输出不是您想要的,那么您可以根据需要调整最后一行。

示例代码最后一行中的
行是什么?什么是
search\u results
?我刚刚编辑了代码-search\u results是我将匹配行转储到的文件的名称。谢谢!!我执行了代码,创建了一个输出文件(output.txt),没有收到任何错误,但输出文件中没有显示任何数据。您知道为什么会这样吗?将内容写入输出文件的唯一时间是单元格的值是否在要匹配的字符串集中(本例中为MRN)。您的字符串可能与单元格值不完全匹配,这是MRN中cell.value的
行中发生的情况。这可能是因为区分大小写、空格或其他原因,所以您可能需要使用一些正则表达式。嘿,凯文,再次感谢!我有一个测试在那里,所以至少有一个匹配应该出现,但它不是。字符串都是数字的,因此不存在区分大小写的问题。我不知道该怎么办,我还是没有结果。不客气。您是否有一些可以添加到问题中的示例输入和字符串?它可以使测试和调试变得更容易。