gpt4 book ai didi

python - 在关键字python正则表达式之后提取信息

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:55 25 4
gpt4 key购买 nike

我正在读取一个文件,其中的数据行如下所示:

ifgfilename: 150304SN.0045; Channel: 1; Name of location: Boulder; Latitude of location: 40.038; Longitude of location: -105.243;

我需要提取信息,因此我编写了如下正则表达式代码:

import re

with open('/Users/CALPY output/info.txt', 'rt') as infofile:
for count, line in enumerate(infofile):
with open('\\_spec_final.t15', 'w') as t:
lat = re.search('^Latitude of location: (.*)', line)
lon = re.search('^Longitude of location: (.*)', line)
date = re.search('^Time of measurement (UTC): (.*)', line)

print lat
print lon
print date

但是,它没有检索我想要的信息,因为它只是打印出来:

None
None
None

知道如何检索我需要的号码吗? (有时我需要字符串,所以我需要一些灵活的东西)

最佳答案

看来您没有必要在每个正则表达式的开头包含 ^ ,这意味着行的开头。还将 .* 更改为除分号 ([^;]+) 之外的所有字符的集合,以匹配所需的值。在我的测试中,我的大小写错误,您可能会因为同样的原因而得到 None ,所以我也添加了这一点。

lat = re.search('Latitude of location:\s*([^;]+)', line, re.IGNORECASE)
lon = re.search('Longitude of location:\s*([^;]+)', line, re.IGNORECASE)
date = re.search('Time of measurement (UTC):\s*([^;]+)', line, re.IGNORECASE)

print lat.group(1)
print lon.group(1)
print date.group(1)

Python 还支持向后查找,因此可以避免不必要的分组的替代方案是:

(?<=Latitude of location: )[^;]+

关于python - 在关键字python正则表达式之后提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38467552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com