1

私はまだPythonに非常に慣れていませんが、NOAAから天気を解析し、ラジオ放送の順序で表示するコードを作成しようとしています。

htmlファイルが行のリストに切り刻まれて適切な順序で再出力されるPython式を使用する現在の条件リストをまとめることができましたが、それぞれが1行のデータでした。そのコードは次のようになりました。

#other function downloads  
#http://www.arh.noaa.gov/wmofcst_pf.php?wmo=ASAK48PAFC&type=public
#and renames it currents.html
from bs4 import BeautifulSoup as bs
import re
soup = bs(open('currents.html')
weatherRaw = soup.pre.string
towns = ['PAOM', 'PAUN', 'PAGM', 'PASA']
townOut = []
weatherLines = weatherRaw.splitlines()
for i in range(len(towns)):
    p = re.compile(towns[i] + '.*')
    for line in weatherLines:
        matched = p.match(line)
        if matched:
            townOut.append(matched.group())

予測部分に取り組んでいるので、問題が発生しています。各予測は必然的に複数の行にまたがって実行され、ファイルを行のリストに切り刻んだからです。

つまり、私が探しているのは、同様のループを使用できるようにする式です。今回は、見つかった行で追加を開始し、&&だけを含む行で終了します。このようなもの:

#sample data from http://www.arh.noaa.gov/wmofcst.php?wmo=FPAK52PAFG&type=public
#BeautifulSouped into list fcst (forecast.pre.get_text().splitlines())
zones = ['AKZ214', 'AKZ215', 'AKZ213'] #note the out-of-numerical-order zones
weatherFull = []
for i in range(len(zones)):
    start = re.compile(zones[i] '.*')
    end = re.compile('&&')
    for line in fcst:
        matched = start.match(line)
        if matched:
            weatherFull.append(matched.group())
            #and the other lines of various contents and length
            #until reaching the end match object

このコードを改善するにはどうすればよいですか?非常に冗長であることはわかっていますが、始めている間は、自分が何をしていたかを追跡できるのが好きでした。前もって感謝します!

4

1 に答える 1

0

これがあなたが求めていたものではない場合はお詫びします(その場合は、調整してください)。BeautifulSoupを使用しているのは素晴らしいことですが、実際にはさらに一歩進めることができます。HTMLを見ると、各ブロックは<a name=zone>構造体で始まり、次のブロックで終わっているように見えます<a name=zone>。その場合、次のようにして、各ゾーンに対応するHTMLをプルできます。

from bs4 import BeautifulSoup

# I put the HTML in a file, but this will work with a URL as well
with open('weather.html', 'r') as f:
  fcst = f.read()

# Turn the html into a navigable soup object
soup = BeautifulSoup(fcst)

# Define your zones
zones = ['AKZ214', 'AKZ215', 'AKZ213']

weatherFull = []

# This is a more Pythonic loop structure - instead of looping over
# a range of len(zones), simply iterate over each element itself
for zone in zones:
  # Here we use BS's built-in 'find' function to find the 'a' element
  # with a name = the zone in question (as this is the pattern).
  zone_node = soup.find('a', {'name': zone})

  # This loop will continue to cycle through the elements after the 'a'
  # tag until it hits another 'a' (this is highly structure dependent :) )
  while True:
    weatherFull.append(zone_node)
    # Set the tag node = to the next node
    zone_node = zone_node.nextSibling
    # If the next node's tag name = 'a', break out and go to the next zone
    if getattr(zone_node, 'name', None)  == 'a':
      break

# Process weatherFull however you like
print weatherFull

これがお役に立てば幸いです(または、少なくともあなたが望んでいたものの球場のどこかにあります!)。

于 2012-10-29T01:41:15.573 に答える