需要帮助从文件中提取数据

时间:2015-04-27 23:59:10

标签: python regex file-io

我是python的新手。

所以我的文件看起来像这样:

  

-1 1:-0.294118 2:0.487437 3:0.180328 4:-0.292929 5:-1 6:0.00149028 7:-0.53117 8:-0.0333333

我需要帮助提供正确的python代码来提取前面有冒号并后跟空格的每个浮点数(例如:[-0.294118, 0.487437,etc...]

我已经尝试了dataList = re.findall(':(.\*) ', str(line))dataList = re.split(':(.\*) ', str(line)),但这些都提出了整行。我已经研究了这个问题一段时间了,所以任何帮助都会受到赞赏。谢谢!

4 个答案:

答案 0 :(得分:1)

试试这个:

:(-?\d\.\d+)\s

在您的代码中

p = re.compile(':(-?\d\.\d+)\s')
m = p.match(str(line))
dataList = m.groups()

这更具体地说明你想要什么。

在你的情况下。*将匹配它所能提供的一切

在Regexr.com上测试:

enter image description here

在这种情况下,最后一个元素没有被捕获,因为它没有空间可以跟随,如果这是一个问题,只需从正则表达式中删除\ s

答案 1 :(得分:0)

这样做:

import re
line = "-1 1:-0.294118 2:0.487437 3:0.180328 4:-0.292929 5:-1 6:0.00149028 7:-0.53117 8:-0.0333333"
for match in re.finditer(r"(-?\d\.\d+)", line, re.DOTALL | re.MULTILINE):
    print  match.group(1)

或者:

match = re.search(r"(-?\d\.\d+)", line, re.DOTALL | re.MULTILINE)
if match:
    datalist = match.group(1)
else:
    datalist = ""

输出:

-0.294118
0.487437
0.180328
-0.292929
0.00149028
-0.53117
-0.0333333

Live Python示例:

http://ideone.com/DpiOBq

正则表达式演示:

https://regex101.com/r/nR4wK9/3

正则表达式解释

(-?\d\.\d+)

Match the regex below and capture its match into backreference number 1 «(-?\d\.\d+)»
   Match the character “-” literally «-?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single character that is a “digit” (ASCII 0–9 only) «\d»
   Match the character “.” literally «\.»
   Match a single character that is a “digit” (ASCII 0–9 only) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

答案 2 :(得分:0)

假设:

>>> s='-1 1:-0.294118 2:0.487437 3:0.180328 4:-0.292929 5:-1 6:0.00149028 7:-0.53117 8:-0.0333.333'

使用您的特定数据示例,您可以使用正则表达式获取将成为浮点数一部分的部分:

>>> re.findall(r':([\d.-]+)', s)
['-0.294118', '0.487437', '0.180328', '-0.292929', '-1', '0.00149028', '-0.53117', '-0.0333.333']

您还可以拆分和分区,这将大大加快:

>>> [e.partition(':')[2] for e in s.split() if ':' in e]
['-0.294118', '0.487437', '0.180328', '-0.292929', '-1', '0.00149028', '-0.53117', '-0.0333.333'] 

然后,您可以使用try/exceptmap以及filter将这些转换为浮点数:

>>> def conv(s):
...     try:
...         return float(s)
...     except ValueError:
...         return None 
... 
>>> filter(None, map(conv, [e.partition(':')[2] for e in s.split() if ':' in e]))
[-0.294118, 0.487437, 0.180328, -0.292929, -1.0, 0.00149028, -0.53117, -0.0333333]

答案 3 :(得分:0)

使用列表理解的简单oneliner -

str =  "-1 1:-0.294118 2:0.487437 3:0.180328 4:-0.292929 5:-1 6:0.00149028 7:-0.53117 8:-0.0333333"
[float(s.split()[0]) for s in str.split(':')]

注意:这是最容易理解的(并且可能最快),因为我们没有进行任何正则表达式评估。但这只适用于上述特定情况。 (例如,如果你要获得第二个数字 - 在上面没有那么正确格式化的字符串需要比上面的单个单行程更多的工作)。