[英]replace sub-string in a file using regex with python
suppose I have a file.txt with line假设我有一个 file.txt 行
aaaa = /bbb/ccc/ddd/eee/fff aaaa = /bbb/ccc/ddd/eee/fff
I would like replace ccc with xxx我想用 xxx 替换 ccc
I have tried next without success我尝试了下一个但没有成功
import re
import fileinput
for line in fileinput.input(file.txt, inplace=True):
re.sub(r'(ccc)', 'xxx', line)
Try this:尝试这个:
m = re.sub(r'ccc', r'xxx', "/bbb/ccc/ddd/eee/fff")
#OUTPUT: /bbb/xxx/ddd/eee/fff
Almost the same question has been asked already here . 这里已经提出了几乎相同的问题。 In your case the answer would look like this:
在您的情况下,答案如下所示:
for line in fileinput.input('file.txt', inplace=True):
print(re.sub(r'(ccc)', 'xxx', line), end='')
See above link to learn about alternatives and efficiency.请参阅上面的链接以了解替代方案和效率。 (Also note the quotes around file.txt)
(另请注意 file.txt 周围的引号)
Short explanation:简短说明:
print()
in Python prints lines with a newline character by default. print()
默认打印带有换行符的行。 To prevent this, end=''
needs to be specified as keyword argument.end=''
指定为关键字参数。r'(ccc)'
contains a pair of group parentheses which is not necessary in your case, so you can simply write r'ccc'
as already pointed out by the two previous posts. r'(ccc)'
包含一对在您的情况下不需要的组括号,因此您可以简单地编写r'ccc'
,正如前两篇文章已经指出的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.