使用正则表达式从html文件中提取国家级玩家列表的更好方法

2024-06-12 06:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

问题陈述:

从下面的html代码生成国家级玩家列表

<ul>
    <li>
        Australia
        <ol>
            <li>Steven Smith</li>
            <li>David Warner</li>
        </ol>
    </li>
    <li>
        Bangladesh
        <ol>
            <li>Mashrafe Mortaza</li>
            <li>Tamim Iqbal</li>
        </ol>
    </li>
    <li>
        England
        <ol>
            <li>Eoin Morgan</li>
            <li>Jos Buttler</li>
        </ol>
    </li>
</ul>

预期产量:

澳大利亚-史蒂文史密斯,大卫华纳

孟加拉国-Mashrafe Mortaza,Tamim Iqbal

英格兰-伊恩摩根,乔斯巴特勒

我的代码:

效果很好。我在找更好的代码。请帮帮我。你知道吗

import re

with open('playerlist.html', 'r') as f:
    text = f.read()

mytext = re.sub(r'[\n\t]', '', text)

pat = r'<li>(\w+?)<ol><li>(\w+\s?\w+)</li><li>(\w+\s?\w+)</li>'

cpat = re.compile(pat)

result = cpat.findall(mytext)


for a,b,c in result:
    print('{0}- {1}, {2}'.format(a,b,c))

Tags: 代码textrehtmlliresultulol
1条回答
网友
1楼 · 发布于 2024-06-12 06:24:27

用regex解析xml/html数据从来都不是一个好主意。
使用xml/html解析器。你知道吗

使用xml.etree.ElementTree模块(其中一个解析器)的正确方法。你可以试试别的):

import xml.etree.ElementTree as ET

root = ET.parse('playerlist.html').getroot()
for li in root.findall('.//li[ol]'):
    print(li.text.strip(), '- {}, {}'.format(*(i.text.strip() for i in li.findall('ol/li'))))

输出:

Australia - Steven Smith, David Warner
Bangladesh - Mashrafe Mortaza, Tamim Iqbal
England - Eoin Morgan, Jos Buttler

相关问题 更多 >