查询正则表达式

时间:2018-01-10 20:08:21

标签: python regex

所以,我给了一个HTML文件,其中包含一些国家名称和来自该国家的两名玩家。我必须阅读该html文件,并使用正则表达式以特定格式显示国家和玩家名称。

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>

我必须以这种格式显示它:

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

我已经尝试了一些东西,但到目前为止还没有。这是我到目前为止能够提出的:

>> with open("test.html","r") as f:
      text = f.read()
>> import re
>> pq = re.findall(r'^<li>\n(.+?)\n\t<ol>\n\t<li>(.+?)</li>\n\t<li>(.+?)
               </li>$',text,re.M)

输出如下:

[('Australia', ' Steven smith ', ' David Warner '),
('Bangladesh', ' Mashrafe Mortaza ', ' Tamim Iqbal  '),
('England', ' Eoin Morgan ', ' Jos Buttler ')]

这不是我想要的。国名似乎没问题。但是玩家名称包含标签。我是正规表达的新手,我不完全确定在这里做什么。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以使用解析器和正则表达式的组合:

from bs4 import BeautifulSoup
import re

rx = re.compile(r'''
    ^
    (?P<country>\w+)\s*
    (?P<player1>.+)[\n\r]
    (?P<player2>.+)''', re.MULTILINE | re.VERBOSE)

soup = BeautifulSoup(your_string_here, 'lxml')

players = ["{} - {}, {}".format(m.group('country'), m.group('player1').strip(), m.group('player2').strip()) 
            for item in soup.select('ul > li')
            for m in rx.finditer(item.text)]
print(players)

哪个收益

['Australia - Steven smith, David Warner', 'Bangladesh - Mashrafe Mortaza, Tamim Iqbal', 'England - Eoin Morgan, Jos Buttler']
相关问题