json - python中用正則表達(dá)式去掉字符串中的冒號(hào)
問題描述
初學(xué)python,最近嘗試爬數(shù)據(jù),json字符串的value中有冒號(hào),需要去掉。我的代碼如下。 a和b都是value中會(huì)有冒號(hào)的字符串
import rea = 'Title:’Intern: Customer Experience + Innovation (CX+I) Intern Brands’'b = 'cmp:’Adecco: USA’,cmpesc:’Adecco: USA’'result = re.sub(’^(?:Title|cmp|cmpesc):.+(:)’,’’, a)
代碼執(zhí)行結(jié)果是只剩 Customer Experience + Innovation (CX+I) Intern Brands’,之前的內(nèi)容全被刪除了,而我想要的效果是只刪intern之后的那個(gè)冒號(hào)(title后的冒號(hào)要保留)。請(qǐng)問大家該如何修改?
問題解答
回答1:import reresult = re.sub(’^(Title|cmp|cmpesc:)(.+):(.*)’,’123’,'Title:’Intern: Customer Experience + Innovation (CX+I) Intern Brands’')print(result) # Title:’Intern Customer Experience + Innovation (CX+I) Intern Brands’回答2:
這樣的話:
’’.join(re.split(’(?<![Title|cmp|cmpesc]):’,a))
就好了
回答3:果然是我看錯(cuò)題目了....
回答4:不用去掉冒號(hào),直接變成字典就行了~
>>> a = 'Title:’Intern: Customer Experience + Innovation (CX+I) Intern Brands’';b = 'cmp:’Adecco: USA’,cmpesc:’Adecco: USA’'>>> dict([s.split(’:’,1) for s in a.split(’,’)]){’Title’: '’Intern: Customer Experience + Innovation (CX+I) Intern Brands’'}>>> dict([s.split(’:’,1) for s in b.split(’,’)]){’cmpesc’: '’Adecco: USA’', ’cmp’: '’Adecco: USA’'}>>>
寫成函數(shù)
a = 'Title:’Intern: Customer Experience + Innovation (CX+I) Intern Brands’'b = 'cmp:’Adecco: USA’,cmpesc:’Adecco: USA’'def fn(x): return dict((s.split(’:’,1) for s in x.replace('’','').split(’,’)))print(fn(a))print(fn(b))# {’Title’: ’Intern: Customer Experience + Innovation (CX+I) Intern Brands’}# {’cmp’: ’Adecco: USA’, ’cmpesc’: ’Adecco: USA’}
相關(guān)文章:
1. java中返回一個(gè)對(duì)象,和輸出對(duì)像的值,意義在哪兒2. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?3. python - pandas dataframe如何對(duì)某列的空數(shù)據(jù)位置進(jìn)行update?update的函數(shù)是自定義的,參數(shù)是同一行的另外兩列數(shù)據(jù)4. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?5. docker start -a dockername 老是卡住,什么情況?6. css3 - 純css實(shí)現(xiàn)點(diǎn)擊特效7. apache web server 怎么限制某一個(gè)網(wǎng)站對(duì)服務(wù)器資源的占用?8. javascript - 關(guān)于apply()與call()的問題9. 安全性測(cè)試 - nodejs中如何防m(xù)ySQL注入10. html5 - 請(qǐng)問現(xiàn)在主流的前端自動(dòng)化構(gòu)建工具是哪個(gè)?
