json - python中用正則表達(dá)式去掉字符串中的冒號
問題描述
初學(xué)python,最近嘗試爬數(shù)據(jù),json字符串的value中有冒號,需要去掉。我的代碼如下。 a和b都是value中會有冒號的字符串
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之后的那個冒號(title后的冒號要保留)。請問大家該如何修改?
問題解答
回答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:果然是我看錯題目了....
回答4:不用去掉冒號,直接變成字典就行了~
>>> 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. javascript - node.js promise沒用2. golang - 用IDE看docker源碼時的小問題3. yii2中restful配置好后在nginx下報404錯誤4. 算法 - python 給定一個正整數(shù)a和一個包含任意個正整數(shù)的 列表 b,求所有<=a 的加法組合5. android 如何實現(xiàn)如圖中的鍵盤上的公式及edittext的內(nèi)容展示呢6. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?7. c++ - 如何正確的使用QWebEngineView?8. PHP注冊功能9. php - TP5的登錄驗證問題10. php - 注冊驗證郵箱失效后操作問題
