从基于url的txt-fi中提取密钥数据

2024-06-01 02:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一段代码来分析这个链接weather report处的文本文件,然后找到文件中的行,读取温度的摄氏值并返回它。 温度读数不总是在同一行上,但在同一行上的格式始终相同。在

在阅读了这里关于堆栈溢出的内容之后,我使用了re库和一个在线regex计算器为我获取了一些代码。到目前为止,我得到的是:

import urllib
import re

def noaa_string():
  url = "http://tgftp.nws.noaa.gov/data/observations/metar/decoded/EGHI.TXT"
  noaa_data_string = urllib.request.urlopen(url).read()
  return noaa_data_string.decode("utf-8")


def noaa_temperature(s):
  """takes a string s as returned from noaa_string() as the input argument,
  extracts the temperature in degree Celsius from the string, and returns
  this temperature as an integer number"""
  regex = r"\Temperature........(\d*)"
  matches = re.finditer(regex, noaa_string())

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1
    match = match.group()
    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1
        group = match.group(groupNum)
        print(group)

我得到了这个错误:

^{pr2}$

有没有人对如何修复这个错误/一种更简单的方法来做我正在尝试的事情有什么建议?我觉得我有点把事情复杂化了。。。在


Tags: the代码inredatastringasmatch
1条回答
网友
1楼 · 发布于 2024-06-01 02:39:52

如你所说

... temperature is not always on the same line but it always has the same format on the line.

所以,你不需要正则表达式的复杂性来解决这个问题。在

import urllib.request

def noaa_string():
    request = urllib.request.urlopen(url).read().split(b'\n')
    for row in request:
        if row.startswith(b'Temperature'):
            return row

def noaa_temperature(s):
    return s[s.find(b'(')+1: s.find(b')')]

编辑

如果要以^{}^{}形式返回值,只需使用相应的函数进行转换。在

^{pr2}$

相关问题 更多 >