如何在 Python 中删除只有数值而不删除通配符的行?

How to remove line with only numeric values without wildcard removal in Python?

我有一个包含数字和文本字符串的文本文件

21        05W104222222316011W1KKB            2564 CHURCH STREET
21        05W1045098014                      CHITTOOR PA 17125
                                                  CHECK TRANSACTIONS                            GB KDI01
                                                            TOTALS                                    PAGE 00094    DATE 07/22/21

OPERATION                    ----INPUT NUMBER----       ----REJECTED  TRANSACTIONS----    ------CHECK  EXTRACTS------
COMPANY   CASH ACCOUNT       RECORDS TRANSACTIONS           NUMBER              AMOUNT     NUMBER              AMOUNT

     21      11633                96           24                0                0.00         24            1,059.59

     21                           96           24                0                0.00         24            1,059.59

我正在尝试删除具有数值的行(完整行)

import re

with open("data.txt", 'r') as f:

    for line in f:
        if not all(i.isdigit() for i in line):
            print(line)

输出


OPERATION                    ----INPUT NUMBER----       ----REJECTED  TRANSACTIONS----    ------CHECK  EXTRACTS------

COMPANY   CASH ACCOUNT       RECORDS TRANSACTIONS           NUMBER              AMOUNT     NUMBER              AMOUNT

上面的代码也删除了非数字行...

预期输出

21        05W104222222316011W1KKB            2564 CHURCH STREET
21        05W1045098014                      CHITTOOR PA 17125
                                                  CHECK TRANSACTIONS                            GB KDI01
                                                            TOTALS                                    PAGE 00094    DATE 07/22/21

OPERATION                    ----INPUT NUMBER----       ----REJECTED  TRANSACTIONS----    ------CHECK  EXTRACTS------
COMPANY   CASH ACCOUNT       RECORDS TRANSACTIONS           NUMBER              AMOUNT     NUMBER              AMOUNT

我只想删除没有硬编码的数字行,例如删除 211,059.59 之间的文本。需要动态删除带数字的行。

你不应该只检查 any 数字,你应该检查 all 是否是非数字(或 space).尝试类似的东西:

if not all(ch.isdigit() or ch.isspace() or ch in ",." for ch in line):
    print(line)

或通过正则表达式:

if re.match(r"^[\s\d\.,]*$", line) is None:
    print(line)

或者检查是否有任何字符串无法转换为浮点数:

try:
    list(map(lambda value: float(value.replace(",", "")), line.split()))
except Exception as error:
    print(line)