-2

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

F00DY4302B8JRQ 等级=0000030 x=800.0 y=1412.0 长度=89

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

感谢大家

4

3 回答 3

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

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

于 2009-12-29T04:09:56.813 回答
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()
于 2009-12-29T04:10:42.523 回答
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()

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

PS 在我写这篇文章时出现了两个答案。我不是西部最快的枪。

于 2009-12-29T04:12:49.037 回答