簡體   English   中英

正則表達式返回Python中的列表?

[英]Regular expression to return list in Python?

因此,我想用大量HTML代碼在Python中列出一個列表,但是我試圖根據HTML標簽對其進行拆分。 我不熟悉正則表達式,所以我不知道該怎么做。 例如,假設我有這段HT​​ML代碼:

<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"]

反正我能做到嗎?

我同意@roippi的評論,請使用HTML解析器。 但是,如果您確實要使用正則表達式,則需要以下內容:

import re

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

>>> print re.findall(r'>\s*([^<]+?)\s*<', s)
['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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM