首页 > 解决方案 > 如何在文件中从字符“xxx”读取和写入字符“yyy”

问题描述

我需要从文本文件中提取数据。在内部,每个学生记录由 20-30 行组成。我正在尝试提取每个学生的相关信息 - 然后将其放入 excel 中。我可以提取学生信息 - 因为他们被标记为姓名:、ID# 等。

我想出了如何打开文本文件并使用标签提取数据并将其写入另一个文本文件。但是我也需要每个学生都有一个块(可变数量的行) - 并且无法弄清楚如何阅读和写作。

对于每个学生,第一行总是以“Ref No”开头......然后是一些行,然后以“======”结尾。在我到达 ===== 之前,我无法弄清楚如何从 Ref No 开始阅读并将所有行写入文本文件。然后继续下一个学生记录。

添加文本示例
名称:john smith
ID:1234456 应付
金额:0.00 美元
参考编号日期代码费用付款余额
001234 12/6/18 BA 123.00 0 123.00 002345
12/7/18 DE 1000.00 1000.00 0
总计:1123.00 1000.00 12===。
==== ======= =======
姓名:Sally Smith
ID 等

一切正常,直到您到达注释掉的区域:

outfile = open('Output.txt', 'w')
with open('ARSP_MGRIFFIT_3728.txt','r') as inFile:
for line in inFile:
    line = line.strip()
    if line.find( 'Name') != -1:
        outfile.write(line + "\n")
    if line.find( 'ID#' ) != -1:
        outfile.write(line + "\n")
    if line.find( 'Term...:' ) != -1:
        outfile.write(line + "\n")
    if line.find( 'Amount Due' ) != -1:
        balance = line[:20]
        outfile.write(balance + "\n")
#        if line.startswith ('Reg No'):
#            flag=True
#            if flag:
#                data.append(line)
#            if line.strip().endswith('==='):
#                flag=False
#            outfile.write(data)

标签: pythonpython-3.x

解决方案


(Name(.[^=]|\n|\r)*)+根据需要对数据块使用正则表达式:

import re

with open('ARSP_MGRIFFIT_3728.txt', 'r') as f:
    data = f.read()

matches = re.findall('(Name(.[^=]|\n|\r)*)+', data)
print(matches)

解释:

  • ()+- 外部组,这会找到多个组
  • Name- 确保组必须包含Name
  • (.[^=]|\n\r)*匹配除=换行符和换行符以外的任何字符

应用它会产生如下输出:

Name: john smith
ID: 1234456
Amount Due: $0.00
Ref No   Date    Code   Charges  Payment   Balance
001234   12/6/18  BA     123.00   0        123.00
002345   12/7/18  DE    1000.00  1000.00   0
                Total:   1123.00 1000.00   123.00
                      <-- added to emphasize the whitespace matched up to the '='
...

推荐阅读