2017-10-21 68 views
0

我正在爲包含數學常量的網頁開發Web解析器。我需要替換一些字符才能使其具有特定格式,但我不知道爲什麼如果我打印它,我似乎工作正常;但是當我打開輸出文件時,replace()所實現的格式似乎不起作用。Python:替換()不會影響寫入文件

這是代碼

#!/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

謝謝你, 薩爾瓦

+1

變量不能在'print'和'f.write'行之間更改它的值。我懷疑你在看錯文件。 – Barmar

回答

0

我一直在尋找的文件是catched所以沒有變化在哪裏看到。感謝您的回答