这是完成这项工作的代码:
import re
# this is the same data just copy/pasted from your question
data = """ ahi1
b/se
ahi
test -2.435953
1.218364
ahi2
b/se
ahi
test -2.001858
1.303935"""
# what we're gonna do, is search through it line-by-line
# and parse out the numbers, using regular expressions
# what this basically does is, look for any number of characters
# that aren't digits or '-' [^-\d] ^ means NOT
# then look for 0 or 1 dashes ('-') followed by one or more decimals
# and a dot and decimals again: [\-]{0,1}\d+\.\d+
# and then the same as first..
pattern = re.compile(r"[^-\d]*([\-]{0,1}\d+\.\d+)[^-\d]*")
results = []
for line in data.split("\n"):
match = pattern.match(line)
if match:
results.append(match.groups()[0])
pairs = []
i = 0
end = len(results)
while i < end - 1:
pairs.append((results[i], results[i+1]))
i += 2
for p in pairs:
print "%s, %s" % (p[0], p[1])
输出:
>>>
-2.435953, 1.218364
-2.001858, 1.303935
您可以将它们保存在一个列表中,然后将它们压缩在一起,而不是打印出来。我正在使用python 正则表达式框架来解析文本。如果您还不知道,我只能建议您选择正则表达式。我发现解析文本和各种机器生成的输出文件非常有用。
编辑:
哦,顺便说一句,如果您担心性能,我在我的慢旧 2ghz IBM T60 笔记本电脑上进行了测试,我可以使用正则表达式在大约 200 毫秒内解析一兆字节。
更新:我感觉很好,所以我为你做了最后一步:P