我有一個文件,其中i具有多個記錄與這種數據刪除基於邏輯
F00DY4302B8JRQ秩= 0000030 X = 800.0 Y = 1412.0長度的線= 89
現在我想搜索行如果我找到長度< = 50然後刪除此行和文件中的下一行並寫入到另一個文件。
謝謝大家
我有一個文件,其中i具有多個記錄與這種數據刪除基於邏輯
F00DY4302B8JRQ秩= 0000030 X = 800.0 Y = 1412.0長度的線= 89
現在我想搜索行如果我找到長度< = 50然後刪除此行和文件中的下一行並寫入到另一個文件。
謝謝大家
從我的頭頂:
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
希望這是你需要開始工作的。
假設的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()
如果列總是以相同的順序和總有相同的號碼,你可以只使用弦上.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.我寫這篇文章時出現了兩個答案。我不是西部最快的槍。
也許你應該向東移動? – Tom 2009-12-29 04:13:58
買不起馬車票價。 – steveha 2009-12-29 04:15:47