【问题标题】:Removing lines that contain a specific number in Python在 Python 中删除包含特定数字的行
【发布时间】:2020-06-04 19:00:48
【问题描述】:

我想知道是否有办法从包含特定数字(或数字)的文件中删除行。

我知道有一种方法可以删除包含特定字符串的行,但我想删除包含特定数字的行。

假设我有一个包含以下数据的文本文件:

201 740 0
202 288 4
202 294 3
202 330 5
202 358 1
202 259 0

我想删除包含数字 0 的行,只是 0(不是 201、202 或任何其他包含 0 的数字)。

我希望示例输出为:

201 740 0
202 259 0

我该怎么做呢?

我尝试了以下方法:

with open('oldfile.txt') as infile, open('newfile.txt', 'w') as outfile:
    for line in infile:
        if '0':
            outfile.write(line)

但它仍然会写每一行,我只想要那些本身有数字 0 的行。

提前致谢!

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    你可以试试:

    if line.strip().endswith(" 0"):
        pass
    else:
        outfile.write(line)
    

    跳过outfile中以“0”结尾的行

    【讨论】:

    • 我实际上只想要其中包含“0”的行。但这实际上是一个很好的解决方案。将 if 语句更改为 if-not 语句,它按预期工作。非常感谢!
    【解决方案2】:

    试试这个:

    with open('oldfile.txt') as infile, open('newfile.txt', 'w') as outfile:
        for line in infile:
            if ' 0' in line:
                outfile.write(line)
    

    您的逻辑表达式正在尝试查看 if ' 0',这将评估为真。

    你需要检查的是'0'是否在行中,所以if ' 0' in line:

    【讨论】:

    • 我试过了,它仍然在输出每一行。也许它无法识别“0”之前的空白?
    • @andresc23 真的吗?你包括if ' 0' in line 吗? in line 部分是实际进行检查的部分
    • 糟糕。我没有,那是我的错。我不知何故错过了那部分。我修复了它,它工作得很好,并给出了预期的输出。谢谢!
    • 如果数据有前导零,这将产生错误的输出:它会错误地匹配这样的行:202 030 5
    【解决方案3】:

    这是一种方法:

    with open('text1.txt','r+') as f:
        f2 = [l for l in f if '0' in l.split()]
    
    with open('text2.txt','w') as f: 
        f.write(''.join(f2))
    

    【讨论】:

      【解决方案4】:

      我想出的大多数通用解决方案都使用正则表达式。这是解决方案。

      import re
      
      with open('oldfile.txt') as infile, open('newfile.txt', 'w') as outfile:
          pattern = re.compile('\D0\D|\D0$|^0\D')
          for line in infile:
              if not pattern.search(line):
                  outfile.write(line)
      

      【讨论】:

        【解决方案5】:
        if '0': 
        

        将始终评估为True,因为非空字符串评估为真。与if 'hello':if True: 相同。

        你想要做的是解析你的行并且只比较最后一个字段

        试试这个:

        with open('oldfile.txt') as infile, open('newfile.txt', 'w') as outfile:
            for line in infile:
                fields = line.split(' ')
                if fields[-1] == '0':
                    outfile.write(line)
        

        line.split(' ') 允许您处理如下所示的列表:

        ['201', '740', '0']
        

        从那里,很容易确保最后一个字段是'0'

        如果您要在任何字段中查找值“0”,也很容易做到这一点:

        with open('oldfile.txt') as infile, open('newfile.txt', 'w') as outfile:
            for line in infile:
                fields = line.split(' ')
                if '0' in fields:
                    outfile.write(line)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-10
          • 2014-10-29
          相关资源
          最近更新 更多