2016-11-03 10 views
1

このリンクのテキストファイルを解析し、ファイル内の行を見つけて温度のCelsius値を読み取り、それを返すコードを少し作ろうとしています。 温度の読みは常に同じ行にあるわけではありませんが、行の形式は常に同じです。URLベースのtxtファイルからキーデータを抽出

ここでスタックオーバーフローでいくつかの読書をした後、私はreライブラリとオンライン正規表現の計算機を使用してコードを取得しました。これは私がこれまで持っているものです。

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()':マッチオブジェクトを破棄し、文字列で置き換えます。 –

答えて

-1

...感じます。

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またはfloatとして値を返すようにしたい場合。

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

ありがとう、私はそれを複雑にするかもしれないと思った!そのコードから返される値はb '12 C'です。どのように整数だけを返すことができますか? –

関連する問題