【发布时间】:2017-10-21 00:08:22
【问题描述】:
我正在为包含数学常数的网页开发网络解析器。我需要替换一些字符才能使其具有特定格式,但我不知道为什么如果我打印它,我似乎工作正常;但是当我打开输出文件时,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()
这就是打印所显示的:
这就是我在输出文件中得到的内容
谢谢你, 萨尔瓦
【问题讨论】:
-
变量不能在
print和f.write行之间改变它的值。我怀疑您查看的文件有误。
标签: python beautifulsoup urllib2