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. android - 安卓做前端,PHP做后台服务器 有什么需要注意的?2. angular.js - 通过数据中children的个数自动生成能点击展开的div3. python的bs4如何筛选出h1标签中的内容4. javascript - 移动端H5页面禁止缩放了,在浏览器上仍然可以缩放5. docker gitlab 如何git clone?6. java - spring-data Jpa 不需要执行save 语句,Set字段就可以自动执行保存的方法?求解7. css - 使用blur()滤镜为什么有透明的效果8. docker-compose 为何找不到配置文件?9. javascript - Vue.js2.0不能使用debounce后大伙一般是如何解决延迟请求的问题的呢。10. Android下,rxJava+retrofit 并发上传文件和串行上传文件的效率为什么差不多?
