1
以下Python代碼:選項端= 「」 在python print()函數不工作始終
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()方法在每種情況下均由內容處理程序應用。但結果卻不盡相同,這使得整件事情變得非常奇怪。
你可以嘗試用'sys.stdout.write(content)'替換'print(「{}」.format(content),end =「」)',看看它是否有所作爲。 –
字符()在僅用換行符打印「apfel」後再次被調用。 –
@TylerBindon你爲什麼這麼認爲? –