我在网上找到了这些代码。
strTable = "<html><table><tr><th>Address</th><th>Name</th></tr>"
for num in range(33,48):
symb = chr(num)
strRW = "<tr><td>"+str(symb)+ "</td><td>"+str(num)+"</td></tr>"
strTable = strTable+strRW
strTable = strTable+"</table></html>"
hs = open("record.html", 'w')
hs.write(strTable)
print (strTable)
正如你所看到的,这个函数会自动打开一个文件名 record.html,它会将 num 范围(33 到 48)symb + num 写入这个 record.html 文件中,这样我就可以将它视为 html。所以现在我想将此代码与我的其他代码结合起来
import xml.etree.ElementTree as ET
root_node = ET.parse('record.xml').getroot()
for tag in root_node.findall('restaurant'):
value = tag.attrib['name']
print("Restaurant name:")
print(value)
for capacity in tag.findall('address'):
print("Address:")
print(address.text)
我想要的是如何将这两个代码结合起来,该函数将自动创建一个文件名“record.html”,并在此文件中自动写入此记录中所有餐厅的餐厅名称和地址的 XML 内容。 html文件?这是我的 xml 代码
<?xml version="1.0" encoding="UTF-8"?>
<record>
<restaurant name="La Pasteria" rate="1">
<cuisine id="-">Italian</cuisine>
<address>8, Jalan Mata Kuching, 89200 Selangor</address>
<capacity>300</capacity>
<phone>06-2899808</phone>
<phone>06-2829818</phone>
<general>-</general>
<shop1>-</shop1>
<shop2>-</shop2>
</restaurant>
<restaurant name="Nyonya Baba" rate="2">
<cuisine id="112">Malaysian</cuisine>
<address>21, Jalan Taming Sari, 75350 Melaka</address>
<address>25, Jalan Bukit Beruang, 75450 Melaka</address>
<capacity>80</capacity>
<phone>
<general>012-2677498</general>
<shop1>06-2855413</shop1>
<shop2>06-2856418</shop2>
</phone>
</restaurant>
</record>
你当然可以。
最好将关注点分开:
read_restaurants
读取 XML 文件并生成餐厅名称和地址的字典generate_record_html
调用它并相应地编写 HTML。import xml.etree.ElementTree as ET
def read_restaurants():
root_node = ET.parse("record.xml").getroot()
for tag in root_node.findall("restaurant"):
value = tag.attrib["name"]
restaurant = {"name": value, "addresses": []}
for address in tag.findall("address"):
restaurant["addresses"].append(address.text)
yield restaurant
def write_record_html():
with open("record.html", "w") as f:
f.write("<html><table><tr><th>Name</th><th>Address</th></tr>")
for restaurant in read_restaurants():
for address in restaurant["addresses"]:
f.write(
"<tr><td>"
+ restaurant["name"]
+ "</td><td>"
+ address
+ "</td></tr>\n"
)
f.write("</table></html>")
write_record_html()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句