[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python
How to replace the first word in a series of occurrences like below.如何替换一系列出现中的第一个单词,如下所示。
Im trying to replace the first "/" in each line(if present) with a "", if not present, go to the next line in a text file.我试图用“”替换每行(如果存在)中的第一个“/”,如果不存在,go 到文本文件的下一行。
ex: in.txt例如:in.txt
Stackover flow /abc/one/two
is suitable to search three/four/five
answers for all /six/seven/eight
output like: output 喜欢:
Stackover flow abc/one/two
is suitable to search three/four/five
answers for all six/seven/eight
I have tried re.sub with various combinations but not able to get any suitable answers.我已经尝试了各种组合的 re.sub,但无法得到任何合适的答案。 I hope to find answers here.
我希望在这里找到答案。 Thanks in advance.
提前致谢。
You can split the string with "/" and join again ignoring the first split.您可以使用“/”拆分字符串并再次加入忽略第一个拆分。
split = _str.split("/")
_new_str = split[0]+"/".join(split[1:])
If I understand the question correctly, you only try to change the first '/' when it's at the beginning of some list of options, eg '/abc/def/ghi', but not when it is between words, eg 'abc/def/ghi'.如果我正确理解了这个问题,您只尝试更改位于某些选项列表开头的第一个“/”,例如“/abc/def/ghi”,而不是在单词之间,例如“abc/”定义/ghi'。
This replaces '/' only if they are at the beginning of a word (per your example):仅当它们位于单词的开头时才会替换“/”(根据您的示例):
import re
with open('in.txt', 'r') as input_file, open('out.txt', 'w') as output_file:
for row in input_file:
new_row = re.sub('\s/', ' ', row)
output_file.write(new_row)
If you want to change the original file, I will refer you here which is quite a nice explanation of why it is not a good idea.如果您想更改原始文件,我会在这里向您推荐,这很好地解释了为什么这不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.