[英]How to extract column data from a text in python (regex)
假設我們有文本,其中列標題存儲在表單中:
{|
|+ 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
|}
如何從python中的文本中提取所有列([ 列標題1 , 列標題2 , 列標題3 ])?
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.