【问题标题】:option end="" in python print() function does not work consistentlypython print() 函数中的选项 end="" 无法始终如一地工作
【发布时间】:2016-12-24 21:38:54
【问题描述】:

以下python代码:

import xml.sax

class C_Handler(xml.sax.ContentHandler):

    def startDocument(self):
        print("<html><head><title>Lieferungen</title></head>")
        print("<body><h1>Lieferungen</h1><hr>\n")
        print("<table border=\"1\"><tr><th>Nummer</th><th>Artikel</th><th>preis</th><th>Lieferant</th></tr>\n")


    def startElement(self, tag, attributes): 
        if tag == "artikel":
            print("<tr><td>{}</td> <td>".format(attributes["id"]),end="")
        if tag == "preis":
            print("</td> <td>", end="")
        if tag == "lieferant":
            print("</td> <td>", end="")

    def endElement(self, tag):
        if tag == "lieferant":
            print("</td> </tr>")

    def characters(self, content):
        print("{}".format(content), end="")

    def endDocument(self):
        print("\n</table>\n</body>\n</html>\n")

if ( __name__ == "__main__"):

    c = C_Handler()

    xml.sax.parse("lieferungen.xml", c)

应该转换以下 xml 文件:

<?xml version="1.0"?>
<lieferungen>
     <artikel id="3526">
         <name>apfel</name>
         <preis stueckpreis="true">8.97</preis>
         <lieferant>Fa. Krause</lieferant>
     </artikel>
</lieferungen>

进入以下输出:

<html><head><title>Lieferungen</title></head>
<body><h1>Lieferungen</h1><hr>

<table border="1"><tr><th>Nummer</th><th>Artikel</th><th>preis</th><th>Lieferant</th></tr>

<tr><td>3526</td> <td> apfel </td> <td> 8.97 </td> <td> Fa. Krause </td> </tr>

</table>
</body>
</html>

但是,我得到的是:

<html><head><title>Lieferungen</title></head>
<body><h1>Lieferungen</h1><hr>

<table border="1"><tr><th>Nummer</th><th>Artikel</th><th>preis</th>   <th>Lieferant</th></tr>


     <tr><td>3526</td> <td> 
        apfel  
       </td> <td> 8.97  
       </td> <td> Fa. Krause </td> </tr>

</table>
</body>
</html>

换句话说:打印函数中的 end="" 选项不能按预期工作。奇怪的是: 有时它起作用(在“Fa. Krause”之后),而在其他情况下(例如在“apfel”之后)它不起作用。由于“Fa. Krause”和“apfel”都是字符数据,因此内容处理程序在每种情况下都会应用 characters() 方法。尽管如此,结果还是不一样,这让整个事情变得非常奇怪。

【问题讨论】:

  • 您可以尝试将print("{}".format(content), end="") 替换为sys.stdout.write(content) 看看是否有效果。
  • characters() 在仅用换行符打印“apfel”后再次被调用。
  • @TylerBindon 你为什么这么认为?
  • 我在本地运行它并将打印字符放在 end="" 中。 characters() 被调用的次数比你预期的要多。

标签: python printing sax


【解决方案1】:

似乎解析器调用 characters() 时使用标签之间的空格,并且该空格包含换行符,这些换行符会打印在预期输出不匹配的位置。

删除示例 xml 文档中标记之间的所有空格使实际输出与预期匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多