2017-10-21 7 views
0

私は数学定数を含むWebページのWebパーサーに取り組んでいます。私は特定の形式でそれを持つためにいくつかの文字を置き換える必要がありますが、私はそれを印刷すると、私はうまく動作しているようだがわからない。しかし、私が出力ファイルを開くと、replace()によって達成されたフォーマットは有効にならなかったようです。表示するものと印刷されたコードPython:Replace()はファイルへの書き込みに影響を与えません。

#!/usr/bin/env python3 

from urllib.request import urlopen 
from bs4 import BeautifulSoup 

url = "http://www.ebyte.it/library/educards/constants/ConstantsOfPhysicsAndMath.html" 
soup = BeautifulSoup(urlopen(url).read(), "html5lib") 
f = open("ebyteParse-output.txt", "w") 

table = soup.find("table", attrs={"class": "grid9"}) 

rows = table.findAll("tr") 
for tr in rows: 
    # If its a category of constants we write that as a comment 
    if tr.has_attr("bgcolor"): 
     f.write("\n\n# " + tr.find(text=True) + "\n") 
     continue 

    cols = tr.findAll("td") 
    if (len(cols) >= 2): 
     if (cols[0]["class"][0] == "box" or cols[0]["class"][0] == "boxi" and cols[1]["class"][0] == "boxa"): 
      constant = str(cols[0].find(text=True)).replace(" ", "-") 
      value = str(cols[1].find(text=True)) 
      value = value.replace(" ", "").replace("...", "").replace("[", "").replace("]", "") 
      print(constant + "\t" + value) 
      f.write(constant + "\t" + value) 

    f.write("\n") 

f.close() 

:私は

enter image description here

おかげ出力ファイルに取得されるものです

enter image description here

、 Salva

+1

変数は 'print'行と' f.write'行の間で値を変更できません。私は間違ったファイルを見ていると思う。 – Barmar

答えて

0

私が探していたファイルはキャッチされていたので、見た目は変わっていません。お返事ありがとう

関連する問題