json - python中用正則表達式去掉字符串中的冒號
問題描述
初學python,最近嘗試爬數據,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)
代碼執行結果是只剩 Customer Experience + Innovation (CX+I) Intern Brands’,之前的內容全被刪除了,而我想要的效果是只刪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’'}>>>
寫成函數
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’}
相關文章:
1. 視頻文件不能播放,怎么辦?2. 前端 - 誰來解釋下這兩個 CSS selector 區別3. javascript - 求幫助 , ATOM不顯示界面!!!!4. javascript - ios返回不執行js怎么解決?5. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題6. html5 - HTML代碼中的文字亂碼是怎么回事?7. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?8. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處9. javascript - vue2如何獲取v-model變量名10. javascript - angular使從elastichearch中取出的文本高亮顯示,如圖所示
