Python的正则表达式有点新手,我正在尝试解析下面的数据。
代码
thing = soup.find_all('div', {'class' : 'matchheader'})
thing1 = str(thing)
print(thing1)
给我
1. GSL - <b>Global Ship Lease Inc</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16
</div>, <div class="matchheader">
2. SBGI - <b>Sinclair Broadcast Group, Inc.</b> [Media] - Matched DCIX from 07/27/16 to 12/01/16
</div>, <div class="matchheader">
3. WSTC - <b>West Corporation</b> [+2] - Matched DCIX from 07/27/16 to 12/01/16
</div>, <div class="matchheader">
4. TGNA - <b>TEGNA Inc.</b> [N/A] - Matched DCIX from 07/27/16 to 12/01/16
</div>, <div class="matchheader">
5. MLI - <b>MUELLER INDUSTRIES INC</b> [Manufacturing] - Matched DCIX from 07/27/16 to 12/01/16
现在为正则表达式
pattern = "([A-Z])[A-Z]{2,5}(?![A-Z])"
match = re.findall(pattern,thing1)
print(match)
我期待的结果是
['GSL', 'SBGI', 'WSTC', 'TGNA', 'MLI']
但我得到的结果是
['G', 'D', 'S', 'D', 'W', 'D', 'T', 'T', 'D', 'M', 'U', 'S', 'I', 'D']
我很确定第二个 D 来自第一行的 DCIX。
那么问题是我正在使用的正则表达式模式,使用re.findall还是print(match)?
任何帮助将不胜感激。
您的正则表达式将匹配每组连续的大写字母,然后只返回每组的第一个字母。相反,您可能打算每行只返回这些组中的第一个。
相反,您可以使用前缀^.*?([A-Z]{2,5})
查找行^.*?
开头的最短序列(对多行模式使用re.M
),后跟一组大写字母([A-Z]{2,5})
(如果有),然后返回该组。
>>> re.findall("^.*?([A-Z]{2,5})", thing1, re.M)
['GSL', 'SBGI', 'WSTC', 'TGNA', 'MLI']
如果是换行文本,或者为了确保我们得到第二行元素(如果类名为空),我建议检查行开头的数字是否存在,并使用以下正则表达式:
r"^[0-9]+[^w]+([A-Z]{2,5})"
我不完全确定,但也许你想要的是soup.text? 即:
for item in thing:
thing1=item.text
print(thing1)
但是,我会这样做:
thing=soup.select('div.matchheader') #returns a list of divs that have a css class 'matchheader'
thing1_list=[]
for item in thing:
thing1_list.append(item.getText())
希望有帮助