Skip to main content
 首页 » 编程设计

python之从匹配的正则表达式中提取数字数据

2025年05月04日39del

我在一个 csv 文件中有一些温度数据,我只想提取一年中第一个月的温度,所以在处理之后我想要一个 [1.4, -5.8]在下面的例子中。

1866-01-01 00:00:01;1866-02-01 00:00:00;1866-01;1.4;G 
1866-02-01 00:00:01;1866-03-01 00:00:00;1866-02;-3.0;G 
1900-01-01 00:00:01;1900-01-01 00:00:00;1900-01;-5.8;G 

我想用 python 模块 re 来做这件事,但我总是无法掌握正则表达式!例如,我下面的快速测试返回所有行,而我只希望它返回一年中第一个月的条目......

import numpy as np 
import re 
 
 
regex = '\d{4}-01-\d{2}\s\d{2}:\d{2}:\d{2};\d{4}-01-\d{2}\s\d{2}:\d{2}:\d{2};\d{4}-01;[-+]?\d*\.\d+|\d+;G' 
 
with open('test.csv', 'rb') as fid: 
    for line in fid: 
        match = re.findall(regex,line) 
        if match: 
            print line 
            print match 

请您参考如下方法:

使用 csv 模块,指定 ; 作为分隔符。数据中的第三列是YYYY-MM,所以检查是否是第一个月,如果是则打印温度:

import csv 
 
with open('data') as f: 
    for row in csv.reader(f, delimiter=';'): 
        year, month = row[2].split('-') 
        if int(month) == 1: 
            print(row[3]) 

输出

1.4 
-5.8 

For comparison, here is the simplest regex that I could come up with to extract the required value:

import re 
 
with open('data') as f: 
    temperature = re.findall(r'\d{4}-01;(.+?);', f.read()) 
    print('\n'.join(temperature)) 

您可以看到阅读和理解正则表达式比阅读 Python 代码需要更多的努力。

还有一种更简单的方法,它依赖于由固定宽度字段组成的数据:

with open('data') as f: 
    for line in f: 
        if line[45:47] == '01': 
            print(line[48:-3])