假设我们有一个文本,其中列标题存储在表单中:
{|
|+ The table's caption
! scope="col" width="20"style="background-color:#cfcfcf;"align="center" | Column header 1
! scope="col" width="20"style="background-color:#ff55ff;"align="center" | Column header 2
! scope="col" | Column header 3
|-
! scope="row" | Row header 1
| Cell 2 || Cell 3
|-
! scope="row" | Row header A
| Cell B
| Cell C
|}
我如何提取所有的列([列标头1, 列标头2, 列标头3])从python文本?
re.findall('*! scope="col" |', text, re.IGNORECASE)
但是它没有起作用。
https://regex101.com/r/PLKREz/6如何在Python中实现?
您可以在scope="col"
的一行中找到最后一个|
之后的所有子字符串:
import re
data = """
{|
|+ The table's caption
! scope="col" width="20"style="background-color:#cfcfcf;"align="center" | Column header 1
! scope="col" width="20"style="background-color:#ff55ff;"align="center" | Column header 2
! scope="col" | Column header 3
|-
! scope="row" | Row header 1
| Cell 2 || Cell 3
|-
! scope="row" | Row header A
| Cell B
| Cell C
|}"""
print(re.findall(r'scope="col".*?| ([^|]+)$', data, re.MULTILINE))
打印:
['Column header 1', 'Column header 2', 'Column header 3']