【问题标题】:Python: Replace() takes no effect on write to filePython:Replace() 对写入文件没有影响
【发布时间】: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()

这就是打印所显示的:

这就是我在输出文件中得到的内容

谢谢你, 萨尔瓦

【问题讨论】:

  • 变量不能在printf.write 行之间改变它的值。我怀疑您查看的文件有误。

标签: python beautifulsoup urllib2


【解决方案1】:

我正在寻找的文件已被捕获,因此没有看到任何变化。谢谢回复

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2020-11-10
    • 2015-11-04
    • 2010-12-01
    • 2013-10-07
    相关资源
    最近更新 更多