【问题标题】:match string and delete lines up to matched string in python在python中匹配字符串并删除匹配字符串的行
【发布时间】:2017-05-03 08:13:04
【问题描述】:

下面是文件输出

xyz abc
abc xyz
apple orranges fruits 
train bus flight
        airbus greatbus
 vegetables not in place.

我必须找到模式“火车巴士航班”并删除所有上述行,包括火车巴士航班

输出应该是:

     airbus greatbus
 vegetables not in place.

谁能推荐一下。

谢谢

【问题讨论】:

  • 那么你有什么尝试?向我们展示您的代码和您面临的问题

标签: python python-2.7


【解决方案1】:

只需检查每一行是否包含您要查找的文本。

# Assuming the input file is called "input.txt"
with open('input.txt', 'r') as fin:
  # Read all the lines
  buff = iter(fin.readlines())

# For the output file do the following
with open('output.txt', 'w') as fout:
  # Iterate over every line
  for line in buff:
    # Check if the text you look for is not in the line
    if "train bus flight" not in line:
      # If not found check next line
      continue
    else:
      # Another for loop to start from where you are
      for line in buff:
        # Write the rest of the lines
        fout.write(line)

【讨论】:

    【解决方案2】:

    您要删除在该行的任何位置包含所有三个提到的单词的行吗?我不知道为什么 xyz abcabc xyz 行被删除。它们中没有train bus flight

    那么这是一种方法。

    Python 3 解决方案:

    with open("a.txt","r") as fp:
        line_list = fp.readlines()
        for line in line_list:
            if all(word in line for word in ["train", "bus", "flight"])==False:
                print(line[:-1])
    

    输出:

    xyz abc
    abc xyz
    apple orranges fruits 
            airbus greatbus
     vegetables not in place
    

    a.txt:

    xyz abc
    abc xyz
    apple orranges fruits 
    train bus flight
            airbus greatbus
     vegetables not in place.
    

    【讨论】:

    • 我想删除所有行直到字符串 macthed ..这就是那些被删除的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2020-05-26
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多