改进代码以生成结果并搜索文件夹中的所有文件

115 阅读2分钟

在给定的 Python 代码中,报错 "NameError: global name 'array_of_lines_strings' is not defined"。

  • 代码中想要对文件夹中的所有文件进行搜索,但代码中仅搜索了单个文件。

0d81676257aed534fa4158892dd0863.png 2. 解决方案:

  • 解决错误:
    • 在代码中,定义了变量 array_of_lines_strings,但没有赋值。需要在搜索文件中对 array_of_lines_strings 赋值,使其包含文件中的所有行。
  • 搜索文件夹中的所有文件:
    • 使用 Python 的 glob 模块来获取文件夹中所有文件的路径。
    • 使用 os.listdir() 函数获取文件夹中的文件名列表。

代码例子:

import re
import glob
import pandas as pd
import os

# 定义正则表达式
AS = re.compile('approve stipulation between', re.IGNORECASE)
OG = re.compile('Order Granting', re.IGNORECASE)

# 读取术语列表
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
with open(r'C:\Users\234234234234\Desktop\termlist.txt') as f:
    termlist = f.readlines()
termlist = [x.strip().lower().split(' ') for x in termlist]

# 定义函数 `keep()`,用于过滤包含特定术语的行
def keep(line):
    match = AS.findall(line)
    if (len(match) > 0):
        return True

    match = OG.findall(line)
    if (len(match) > 0):
        return True

    return False

# 定义函数 `search()`, 用于搜索文件中特定术语的行
def search(file_name):
    with open(file_name, 'r') as f:
        lines = f.readlines()
    array_of_lines_strings = [x.strip().lower() for x in lines]  # 将文件中的所有行保存到 `array_of_lines_strings` 中
    lines_to_scan = set(array_of_lines_strings)  # 将所有行转换为集合以提高搜索效率
    found_lines_list = []  # 初始化保存找到的行号的列表

    # 遍历文件中的每行
    for line_number in range(1, len(array_of_lines_strings)):
        for search_term in termlist:
            if search_term in lines_to_scan:
                found_lines_list.append([line_number - 1, line_number])

    return found_lines_list

if __name__ == '__main__':
    # 获取文件夹中的所有文件路径
    directoryPath = r'C:\Users\234234234234\Desktop\eric__pdf'
    file_list = glob("C:\Users\234234234234\Desktop\eric_pdf\*.txt")

    # 遍历文件列表中的每个文件
    for file in file_list:
        found_lines_list = search(file)  # 搜索文件中特定术语的行

        # 将搜索结果保存到 DataFrame 中
        results = []
        for line_range in found_lines_list:
            with open(file) as f:
                for line_number in range(line_range[0], line_range[1]):
                    results.append(f.readline())

        df = pd.DataFrame({'results': results})

        # 将 DataFrame 保存为 CSV 文件
        file_name = os.path.basename(file)[:-4]  # 获取文件名的前缀(不包括扩展名)
        df.to_csv(directoryPath + '\' + file_name + '_results.txt')  # 将结果保存到文件中

注意:

  • 需要将 C:\Users\234234234234\Desktop\termlist.txtC:\Users\234234234234\Desktop\eric__pdf 替换为实际的路径。
  • 需要将 directoryPath 变量更改为您想搜索的文件夹的路径。