我们说我们有文本,其中列标题存储在表单中:
{|
|+ 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 ])蟒?
re.findall('*! scope="col" |', text, re.IGNORECASE)
但它没有做好这份工作。
https://regex101.com/r/PLKREz/6
我怎样才能用Python做到这一点?
答案 0 :(得分:0)
您可以在|
行的最后一个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']