2016-11-03 2 views
1

이 링크 weather report에있는 텍스트 파일을 분석 한 다음 파일의 해당 줄을 찾아 온도의 섭씨 값을 읽고 반환하는 코드를 작성하려고합니다. 온도 표시가 항상 같은 줄에있는 것은 아니지만 항상 줄의 형식이 같습니다.URL 기반 txt 파일에서 키 데이터 추출

스택 오버플로에 대한 일부 독서를 한 후에 저는 라이브러리와 온라인 정규식 계산기를 사용하여 일부 코드를 읽었습니다. 나는이 오류가 무엇입니까

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) 

:

File "E:/Google Drive/python_files/untitled0.py", line 26, in <module> 
for groupNum in range(0, len(match.groups())): 

AttributeError: 'str' object has no attribute 'groups' 

사람이 오류를 해결하는 방법에 대한 제안이 않습니다를/쉬운 방법은 내가하려고 무엇을 할 이것은 내가 지금까지 무엇을 가지고 해야 할 것? 나는 일을 조금 복잡 이상입니다처럼 당신이 그래서, 당신은이 문제를 해결하기 위해 정규식의 복잡성을 필요가 없습니다

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

을 말했듯이 나는 ...

+0

for 루프는'noaa_temperature'와 동일한 기능을한다고 가정합니까? – MooingRawr

+4

'match = match.group()': 당신은 match 객체를 파괴하고 그것을 문자열로 대체합니다. –

답변

-1

생각합니다.

당신이 int 또는 float int로서 값을 반환하려면

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')')] 

편집 바로 대응 기능을 사용하여 변환합니다.

int(s[s.find(b'(')+1: s.find(b')')]) 
+1

고마워, 나는 그것을 복잡하게했을지도 모른다라고 생각했다! 해당 코드에서 반환 된 값은 b '12 C'입니다. 어떻게 정수를 반환 할 수 있습니까? –