gpt4 book ai didi

python - Python 中返回列表的正则表达式?

转载 作者:行者123 更新时间:2023-12-01 05:14:50 24 4
gpt4 key购买 nike

所以,我想用 Python 从一大块 HTML 代码中创建一个列表,但我试图根据 HTML 标签将其拆分。我不太熟悉正则表达式,所以我不知道该怎么做。例如,假设我有这段 HTML 代码:

<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>

我希望能够将此代码(尽管是更大的版本)保存到字符串中,然后使用函数返回如下列表:

list = ["Example text here", "Example text here", "Example text here"]

无论如何我可以做到这一点吗?

最佳答案

您可以简单地使用 BeautifulSoup为此目的。

import bs4

html = '''
<option value="674"> Example text here </option>
<option value="673"> Example text here</option>
<option value="672"> Example text here </option>
'''

soup = bs4.BeautifulSoup(html)
mylst = [str(x.text).strip() for x in soup.find_all('option')]

输出

['Example text here', 'Example text here', 'Example text here']

关于python - Python 中返回列表的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419787/

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