Python to replace a symbol between between 2 words in a quote

一笑奈何 提交于 2019-12-11 16:34:00

问题


trying to replace comma between 2 words Durango and PC in the second line by & and then remove the quotes " as well. Same for third line with Orbis and PC I would like to retain the rest of the lines using Python:

2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened
2,Kenny Chong,Core Tech - Rendering,"Durango, PC",55,Reopened
3,SIN-Audio,AAA - Audio,"Orbis, PC",13,Open
...
... 
...

Like these, there can be 100 lines in my sample. So the expected output is:

2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened
2,Kenny Chong,Core Tech - Rendering, Durango & PC,55,Reopened
3,SIN-Audio,AAA - Audio, Orbis & PC,13,Open
...
...
...

So far, I could think of reading line by line and then if the line contains quote replace it with no character but then replacement of symbol inside is something I am stuck with.

How to achieve this, any suggestion? Learning Python.


回答1:


Use a regular expression for this. Write a regular expression that catches your string, and then use it to replace it.

It should look something like this:

\"(\w*),\ (\w*)\"

This will catch your Durango and PC, and map both of them into two groups which you later use when you replace them.




回答2:


Something like this? Add proper if() if you want to switch comma to ampersand only in second line:

This code goes trough all lines with ..., "..., ...", ... => ..., ... & ..., ...

import re

expr = r'2,Kenny Chong,Core Tech - Rendering,"Durango, PC",55,Reopened'

expr2 =  re.findall('"(.*?)"', expr)
if len(expr2)!=0:
    expr3 = re.split('"',expr)
    expr4 = expr3[0]+expr3[1].replace(","," &")+expr3[2]
    print(expr4)



回答3:


Something like below:

st = "2,Kenny Chong,Core Tech - Rendering,\"Durango, PC\",55,Reopened"
res = re.sub(r'\"(.*),\ (.*)\"',lambda x : (" & ").join(re.findall(r'\"(.*),\ (.*)\"', st)[0]),st)


来源:https://stackoverflow.com/questions/51609461/python-to-replace-a-symbol-between-between-2-words-in-a-quote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!