匹配字符串并删除python中匹配字符串的行

时间:2017-05-03 08:13:05

标签: python python-2.7

以下是文件输出

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

我必须找到模式“火车公共汽车航班”并删除以上所有线路包括火车公共汽车的航班

输出应该是:

     airbus greatbus
 vegetables not in place.

有人可以建议。

由于

2 个答案:

答案 0 :(得分:0)

您是否要删除在该行的任何位置具有所有三个提到的单词的行?我不知道为什么 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.

答案 1 :(得分:0)

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

# 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)