簡體   English   中英

基於正則表達式的Python拆分標簽

[英]Python split tags based on regular expression

我想按以下方式拆分以下標記<b size=5 alt=ref>

Open tag: b
Parm: size=5
Parm: alt=ref

但是,我嘗試使用以下代碼將標記分為幾組,但沒有用:

temp = '<b size=5 alt=ref>'
matchObj = re.search(r"(\S*)\s*(\S*)", temp)
print 'Open tag: ' + matchObj.groups()

我的計划是將標簽分成幾組,然后將第一組打印為開放標簽,其余的打印為Parm。 您能提出任何可以幫助我解決此問題的想法嗎?

請注意,我從html文件中讀取了標簽,但是在這里我提到了打開標簽的示例,並且展示了我堅持使用的代碼部分。

謝謝

tag_names = ["Open tag:","Parm:","Parm:"]
import re  
# split on <,>,white space, and remove empty strings at
# the start and at the end of the resulting list. 
tags = re.split(r'[<> ]','<b size=5 alt=ref>')[1:-1]
# zip tag_names list and with list of tags
print(list(zip(tag_names, tags)))

[('Open tag:', 'b'), ('Parm:', 'size=5'), ('Parm:', 'alt=ref')]
>>> import re
>>> temp = '<b size=5 alt=ref>'
>>> resList  = re.findall("\S+", temp.replace("<","").replace(">",""))
>>> myDict = {}
>>> myDict["Open tag:"] = [resList[0]]
>>> myDict["Parm:"] = resList[1:]
>>> myDict
{'Open tag:': ['b'], 'Parm:': ['size=5', 'alt=ref']}

暫無
暫無

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

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