Python:如何从具有混合内容的文本文件中提取浮点数?
作者:互联网
我有一个制表符分隔的文本文件,其中包含以下数据:
ahi1
b/se
ahi
test -2.435953
1.218364
ahi2
b/se
ahi
test -2.001858
1.303935
我想将两个浮点数提取到具有两列的单独的csv文件中,即.
-2.435953 1.218264
-2.001858 1.303935
目前,我的黑客尝试是:
import csv
from itertools import islice
results = csv.reader(open('test', 'r'), delimiter="\n")
list(islice(results,3))
print results.next()
print results.next()
list(islice(results,3))
print results.next()
print results.next()
这不理想.我是Python的新手,因此我向您致歉,并感谢您的宝贵时间.
解决方法:
这是完成这项工作的代码:
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 regular expression framework解析文本.我只建议您选择不知道的正则表达式.我发现解析文本和各种机器生成的输出文件非常有用.
编辑:
哦,顺便说一句,如果您担心性能,我在速度较慢的2ghz IBM T60笔记本电脑上进行了测试,可以使用正则表达式在200ms内解析出一个兆字节.
更新:
我感到很友善,所以我为您做了最后一步:P
标签:floating-point,tab-delimited,python 来源: https://codeday.me/bug/20191201/2078897.html