2 回答
TA贡献1863条经验 获得超2个赞
您可以BeautifulSoup使用soup.find_all:
from bs4 import BeautifulSoup as soup
r = [i.find_all('word') for i in sorted(soup(html, 'html.parser').find_all('line'), key=lambda x:float(x['ymin']))]
result = [i.text for b in r for i in b]
输出:
['10', '1', 'PC', '20']
TA贡献1877条经验 获得超1个赞
试试下面的代码。可以定义平均值,然后检查平均值。
from bs4 import BeautifulSoup
html='''<flow>
<block xMin="53.879997" yMin="369.965298" xMax="63.939976" yMax="380.991433">
<line xMin="53.879997" yMin="369.965298" xMax="63.939976" yMax="380.991433">
<word xMin="53.879997" yMin="369.965298" xMax="63.939976" yMax="380.991433">10</word>
</line>
</block>
</flow>
<flow>
<block xMin="53.879997" yMin="417.965298" xMax="63.939976" yMax="428.991433">
<line xMin="53.879997" yMin="417.965298" xMax="63.939976" yMax="428.991433">
<word xMin="53.879997" yMin="417.965298" xMax="63.939976" yMax="428.991433">20</word>
</line>
</block>
</flow>
<flow>
<block xMin="111.351361" yMin="369.965298" xMax="134.220382" yMax="380.991433">
<line xMin="111.351361" yMin="369.965298" xMax="134.220382" yMax="380.991433">
<word xMin="111.351361" yMin="369.965298" xMax="116.331548" yMax="380.991433">1</word>
<word xMin="121.909358" yMin="369.965298" xMax="134.220382" yMax="380.991433">PC</word>
</line>
</block>
</flow>'''
soup=BeautifulSoup(html,'lxml')
pricemin=soup.select_one('line[yMin]')['ymin']
list1=[]
list_last=[]
for item in soup.select('line[yMin]'):
if float(pricemin) < float(item['ymin']):
for w in item.select('word'):
list_last.append(w.text)
else:
for w in item.select('word'):
list1.append(w.text)
print(list1+list_last)
输出:
['10', '1', 'PC', '20']
打印这个
print(' '.join(list1+list_last))
输出:
10 1 PC 20
添加回答
举报