【问题标题】:How to extract text in one file based from text in another file using Python如何使用 Python 从另一个文件中的文本提取一个文件中的文本
【发布时间】:2021-11-01 04:27:53
【问题描述】:

我是 Python 新手。我在这里搜索了其他问题,但没有找到我遇到的确切情况。

我需要能够读取 File-A 的内容并从 File-B 中提取匹配的行。

我知道如何在 PowerShell 中执行此操作,但处理大文件时速度非常慢,我正在尝试学习 Python。

文件-A 仅包含贷款编号 - 每行 8 到 10 位数字 File-A 可以包含 1 到数千行

文件-B 可以包含 1 到数千行,其中包含更多数据,但每行将以相同的 8 到 10 位贷款编号开头。

我需要读取 File-A 并在 File-B 中找到匹配的行并将这些匹配的行写到一个新文件中(都是文本文件)

File-A 的示例内容 - 无空格 - 每行 1 次借出

272991
272992
272993

文件-B的示例内容

272991~20210129~\\Serv1\LOC7\675309\867530\016618\272991.pdf~0
272992~20210129~\\Serv1\LOC7\675309\867530\016618\272992.pdf~0
272993~20210129~\\Serv1\LOC7\675309\867530\016618\272993.pdf~0

是否有人能够提供帮助、为我指明正确的方向或更好地提供可行的解决方案?

这是我迄今为止尝试过的,但它所做的只是创建新的 PulledLoans.txt 文件,其中没有任何内容

import os
# os.system('cls')
os.chdir('C:\\Temp\\')
print(os.getcwd())
# read file
loanFile = 'Loans.txt'
SourceFile = 'Orig.txt'
NewFile = 'PulledLoans.txt'

with open(loanFile, 'r') as content, open(SourceFile, 'r') as source:
    # print(content.readlines())
    for loan in content:
        # print(loan, end='')
        if loan in source:
            print('found loan')

with open(SourceFile) as dfile, open(loanFile) as ifile:
    lines = "\n".join(set(dfile.read().splitlines()) & set(ifile.read().splitlines()))
    print(lines)
    
with open(NewFile, 'w') as ofile:
    ofile.write(lines)

【问题讨论】:

  • 哪个是sourcefile,哪个是loanfile?您的代码在哪里查找一个文件中的哪一行与另一个文件中的一行相对应?

标签: python iteration matching string-matching


【解决方案1】:

首先,将 fileB 中的所有内容读入字典,其中键是标识符,值是整行

file_b_data = dict()

with open("fileB") as f_b:
    for line in f_b:
        line = line.strip() # Remove whitespace at start and end
        if not line:
            continue # If the line is blank, skip

        row = line.split("~") # Split by ~
        identifier = row[0]   # First element is the identifier
        file_b_data[identifier] = line # Set the value of the dictionary

接下来,从fileA 中读取行并从字典中获取匹配值

with open("fileA") as f_a, open("outfile", "w") as f_w:
    for identifier in f_a:
        identifier = identifier.strip()
        if not identifier:
            continue
        if identifier in file_b_data: # Check that the identifier exists in previously read data
            out_line = file_b_data[identifier] + "\n" # Get the value from the dict
            f_w.write(out_line) # Write it to output file

或者,您可以使用pandas 模块将所有fielAfileB 读入数据帧,然后找到正确的行。

import pandas as pd

file_b_data = pd.read_csv("fileB.txt", sep="~", names=["identifier", "date", "path", "something"], index_col=0)

这给了我们这个数据框:

identifier date     path                                         something
272991     20210129 \\Serv1\LOC7\675309\867530\016618\272991.pdf 0
272992     20210129 \\Serv1\LOC7\675309\867530\016618\272992.pdf 0
272993     20210129 \\Serv1\LOC7\675309\867530\016618\272993.pdf 0

fileA 也一样:(我删除了 272992 以说明它确实有效)

file_a_data = pd.read_csv("fileA.txt", names="identifier")

给我们

   identifier
0      272991
1      272993

然后,在file_b_data 中查找这些索引:

wanted_ids = file_a_data['identifiers']
wanted_rows = file_b_data.loc[wanted_ids, :]
wanted_rows.to_csv("out_file.txt", sep="~",header=None)

将写入此文件:(注意272992 行丢失,因为它不在fileA 中)

272991~20210129~\\Serv1\LOC7\675309\867530\016618\272991.pdf~0
272993~20210129~\\Serv1\LOC7\675309\867530\016618\272993.pdf~0

【讨论】:

  • 感谢您的回复和代码示例,遗憾的是它们都不适合我。对于 Pandas,我的错误是:ValueError: Duplicate names are not allowed。对于其他代码示例,我得到的错误是: KeyError: '990000071~20210331~\\\\VSPDF04\\PDF7\\77500Z\\77503A\\017426\\990000071.pdf~0'
  • @DataLore 抱歉,我在第二个循环中将line 重命名为identifier,但忘记在答案中的一处进行更改。现在应该修好了。
  • 至于“不允许重复名称”:你的文件有标题吗?在这种情况下,您需要在您的 pd.read_csv() 调用中添加一个 header=None 参数
  • 普拉纳夫-谢谢!正如您在示例更新中指出的那样,我对代码进行了更改,现在可以正常工作了。我很感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2022-01-14
  • 2018-03-29
  • 1970-01-01
  • 2019-03-06
相关资源
最近更新 更多