我經常使用 len(find_all("some_element") 來計算 xml 檔案中物體的數量。我試圖構建一個函式,但它不起作用/它總是給我“無”。
XML檔案:
<parent>
<some>
<child>text</child>
<child>text</child>
<child>text</child>
</some>
</parent>
我的python代碼:
def return_len(para1,para2): # doesn't work
if bool(suppe.para1): # the element isn't always present in the xml
return len(suppe.para1.find_all(para2))
def return_len1(): # does work
if bool(suppe.some):
return len(suppe.some.find_all("child"))
print(return_len("some","child")) # doesnt work
print(return_len1()) # does work
我必須如何修改我的函式 return_len 才能作業/我做錯了什么?
uj5u.com熱心網友回復:
你可以這樣做。
from bs4 import BeautifulSoup
s = """<parent>
<some>
<child>text</child>
<child>text</child>
<child>text</child>
</some>
</parent>
"""
soup = BeautifulSoup(s, 'xml')
def return_len(para1,para2,soup):
print(f'No. of <{para2}> tags inside <{para1}> tag.')
temp = soup.find(para1)
if temp:
return len(temp.find_all(para2))
print(return_len('some', 'child', soup))
print(return_len('parent', 'some', soup))
No. of <child> tags inside <some> tag.
3
No. of <some> tags inside <parent> tag.
1
uj5u.com熱心網友回復:
沒有任何外部庫 - 見下文
import xml.etree.ElementTree as ET
xml = '''<parent>
<some>
<child>text</child>
<child>text</child>
<child>text</child>
</some>
</parent>'''
root = ET.fromstring(xml)
print(f'Number of child elements is {len(root.findall(".//child"))}')
輸出
Number of child elements is 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331659.html
