首页 > 解决方案 > 从多个文本苍蝇中提取,附加结果

问题描述

我写了一个函数来用正则表达式从文本文件中提取。该函数返回每个变量。我有很多文件,想遍历这些文件并附加结果。每个变量都是一个列表;我将结合这些来创建一个 DF。这也有效。

我知道有 glob,但在实施时遇到了麻烦。我过去曾将它用于目录/文件列表。我一直在搜索/阅读很多内容,但显然遗漏了一些明显的东西。

我编写了该函数,并且之前使用过 glob 来列出文件名。我知道 list.append,但不确定如何与 glob(或类似)结合。

如何迭代文件、调用此函数并在每次迭代后附加结果?

文本:

A bunch of sentences
CUSTOMER: 78787
amount (500 dollars)
A bunch of sentences

代码

def find(customer, amount):    
    with open(r"file.txt",'r') as myfile:
        text = myfile.read() 

    customer = re.findall(r"^CUSTOMER:[\s](.*)\d+", text) 
    amount = re.findall(r'\((.*?)\)', text)

    return customer, amount

该功能有效,但仅适用于当前读取的一个文件。

标签: pythonfunctionappendextractglob

解决方案


只需遍历使用您的函数生成的文件列表即可。此外,传入customeror也没有意义amount。它们只是在find函数运行时创建并在返回后持续存在。

您可以使用pathlib.Path'glob方法。开始:

from pathlib import Path

def find(file_name):    
    with open(file_name,'r') as f:
        text = f.read() 

    customer = re.findall(r"^CUSTOMER:[\s](.*)\d+", text) 
    amount = re.findall(r'\((.*?)\)', text)

    return customer, amount

file_dir = Path("path_to_directory_containing_files") # CHANGE THIS
all_files = file_dir.glob("*.txt") # this should be whatever pattern that matches all the input files
results = [find(f) for f in all_files]

推荐阅读