删除基于逻辑的行

时间:2009-12-29 03:52:33

标签: python text-processing

我有一个文件,其中我有多条带有此类数据的记录

  

F00DY4302B8JRQ rank = 0000030 x = 800.0 y = 1412.0 length = 89

现在我想搜索行,如果我找到长度< = 50然后删除此行和文件中的下一行并写入另一个文件。

谢谢大家

3 个答案:

答案 0 :(得分:1)

从头到尾:

for every line in file
split by spaces
get last token
split by equal
verify length
write line to another file
delete line and the next

希望这是你开始工作所需要的。

答案 1 :(得分:1)

假设Python 2.6(让我们知道它是否是您需要的另一个版本!),并且您希望跳过每个行,长度为< = 50(并忽略每种情况下的下一行) ,如果有的话:

import re

def weirdtask(infname, oufname):
  inf = open(infname, 'r')
  ouf = open(oufname, 'w')
  rle = re.compile(r'length=\s*(\d+)')
  for line in inf:
    mo = re.search(line)
    if mo:
      thelen = int(mo.group(1))
      if thelen <= 50:
        next(inf)
        continue
    ouf.write(line)
  ouf.close()

如果这不完全是您的规格,请澄清。

  inf.close()

答案 2 :(得分:0)

如果列总是以相同的顺序并且始终具有相同的数字,则可以在字符串上使用.split()方法,并使用索引找到所需的方法:

words = line.split()
l = words[4]
temp = l.split("=")[2]
if int(temp) <= 50:
    # found the line, handle it
    do_something_here()

如果列可能是任何顺序,则可以使用正则表达式。

s_pat = "length\s*=\s*(\d+)"
pat = re.compile(s_pat)

m = pat.search(line)
if m:
    temp = m.group(1)
    if int(temp) <= 50:
        # found the line, handle it
        do_something_here()

这使用正则表达式中的“匹配组”来获取数字。

P.S。我写这篇文章时出现了两个答案。我不是西方最快的枪。

相关问题