gpt4 book ai didi

python - 正则表达式 : Find Names in String using Python

转载 作者:可可西里 更新时间:2023-11-01 13:10:24 27 4
gpt4 key购买 nike

到目前为止,我在使用正则表达式时从未遇到过困难。我希望解决方案不是很明显,因为我可能已经在这个问题上花了几个小时。

这是我的字符串:

<b>Carson Daly</b>: <a href="https://rads.stackoverflow.com/amzn/click/com/B009DA74O8" rel="nofollow noreferrer">Ben Schwartz</a>, Soko, Jacob Escobedo (R 2/28/14)<br>'

我想将“Soko”和“Jacob Escobedo”提取为单独的字符串。如果我采用两种不同的提取模式,这对我来说没有问题。

我已经尝试过“\s([A-Za-z0-9]{1}.+?)”和该正则表达式的其他更改来获取我想要的数据,但我没有成功。感谢您的帮助。

名称从不遵循相同的标签或相同的符号。唯一始终位于名称前面的是空格 (\s)。

这里以另一个字符串为例:

<b>Carson Daly</b>: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh<br>

最佳答案

另一种方法是使用 HTML 解析器解析字符串,例如 lxml .

例如,您可以使用 xpath 查找包含 Carson Daly 文本的 b 标签和 br 标签之间的所有内容,方法是检查 precedingfollowing sibling :

from lxml.html import fromstring

l = [
"""<b>Carson Daly</b>: <a href="http://rads.stackoverflow.com/amzn/click/B009DA74O8">Ben Schwartz</a>, Soko, Jacob Escobedo (R 2/28/14)<br>'""",
"""<b>Carson Daly</b>: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh<br>"""
]

for html in l:
tree = fromstring(html)
results = ''
for element in tree.xpath('//node()[preceding-sibling::b="Carson Daly" and following-sibling::br]'):
if not isinstance(element, str):
results += element.text.strip()
else:
text = element.strip(':')
if text:
results += text.strip()

print results.split(', ')

它打印:

['Ben Schwartz', 'Soko', 'Jacob Escobedo (R 2/28/14)']
['Wil Wheaton', 'the Birds of Satan', 'Courtney Kemp Agboh']

关于python - 正则表达式 : Find Names in String using Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24091237/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com