python - 如何在文件中从字符 "xxx"到字符 "yyy"读写

标签 python python-3.x

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

我想出了如何打开文本文件并提取带有标签的数据并将其写入另一个文本文件。但是我还需要每个学生一大块(行数可变) - 并且不知道如何阅读和编写它们。

对于每个学生,第一行总是以“Ref No”开头...然后是一些行,最后以“======”结尾。我不知道如何从 Ref No 开始读取并将所有行写入文本文件,直到到达=====。然后继续下一个学生记录。

添加文本示例
姓名:约翰·史密斯
编号:1234456
应付金额:0.00 美元
引用编号 日期代码 费用 付款余额
001234 12/6/18 巴 123.00 0 123.00
002345 12/7/18 德国 1000.00 1000.00 0
总计:1123.00 1000.00 123.00
======= ======= =======
姓名:莎莉·史密斯
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)

最佳答案

在数据上使用正则表达式 (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 '='
...

关于python - 如何在文件中从字符 "xxx"到字符 "yyy"读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54470800/

相关文章:

python - FastAPI - 如何生成随机 ID?

python-3.x - 欧洲/巴黎 -> CET;亚洲/香港-> HKT;欧洲/莫斯科 -> MSK

python - pandas 在每个组中找到满足特定条件的行的索引并为这些行分配值

python : threads; SyntaxError: non-keyword arg after keyword arg

python - 为什么我看不到从 future 导入的 print 函数的参数?

python - 如何更新计数器 : set new value after avery request, 不将新值增加到以前的值?

python - 类和变量

python - 在 Pandas 中添加日期列时出错

python - 如何使用 nargs ='+' 解析多个位置参数

Python:使用梯形规则快速计算平均值