【问题标题】:Extract specific records from a text file and save to a new file in Python从文本文件中提取特定记录并保存到 Python 中的新文件
【发布时间】:2019-10-23 09:30:32
【问题描述】:

我有一个包含数千条收据信息的 txt 文件。 有两种类型:

  • 定期收据

  • 摘要收据

我需要获取所有摘要收据及其内容并将其写入新文件。

以下是我到目前为止所做的,但它所做的只是将所有内容复制到一个新文件中。

filtered = []
with open("sample.txt", "r+") as file: 
    for line in file:
        filtered.append(line.split(""" 
                    Company Name
                      A CITY         
                    Name of CITY              
                     Tin:00000     
                      #10000      
            N#00108235 Cashier ID#0000 
        - - - - - - - - - - - - - - - - - - - -
                Report(X-Report)         
        """))

    outputfile = open("output.txt","w") 
    for lines in filtered:
        outputfile.write(str(lines))

我对 python 很陌生,非常感谢提示或指导。 TIA

【问题讨论】:

  • 那么您的问题是如何识别普通收据的汇总收据?
  • 是的,识别汇总收据并将其保存到单独的文本文件中。
  • 它们的格式都一样吗?一份用于常规,一份用于食谱?
  • 查看正则表达式。 import re 然后使用正则表达式格式对收据的主要内容(项目)进行分组。您可以编辑问题以显示您想要的输出吗?

标签: python python-3.x list


【解决方案1】:

首先我们可以将整个文件拆分成这样的食谱列表。

with open("sample.txt", "r+") as file: 
    receipts = file.read()

# We convert it to a list of receipts
receipts = receipts.split("- - - - -") #<=== This should be tweak to ensure that we split all receipt. You can also use "FROM THE DATE  PERMIT TO USE"

然后我们过滤小时列表,我们在食谱列表中是唯一的。

my_filter = lambda receipt: "SUMMARY OF CHARGE" in receipt
summaries = list(filter(my_filter, receipts)) 

with open("out.txt", "a") as outfile:
    for summary in summaries:
        outfile.write(summary) 

【讨论】:

    【解决方案2】:

    您只需要根据类型将它们分开吗? 根据您的解释,简单的解决方案是读取文件的内容并在该文件中找到“SUMMARY OF CHARGES”一词,如果找到,则将内容保存到新文件中。 任何带有 abc 字样的正则表达式将是 .*abc.* 如果您有单个收据的单个文件,则代码将是这样的。

    import re
    with open("sample.txt","r") as sfile:
       cont=sfile.read()
    if (re.match(".*SUMMARY OF CHARGES.*",cont)):
       with open("outfile.txt","w") as outfile:
          outfile.write(cont)
    

    要分隔各个收据的内容,您可以使用正则表达式组。使正则表达式只保留一张收据,然后创建一个组 (your_regex)* 然后遍历该组以获取所有匹配的收据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多