我的任务是使用 python 将文本文件中的“O”(大写 O)替换为“0”。但一个条件是我必须保留其他词,如 Over、NATO 等。我只需要替换 9OO 到 900、2OO6 到 2006 等词。我尝试了很多但没有成功。我的代码如下。请帮助我任何一个。提前致谢
import re
srcpatt = 'O'
rplpatt = '0'
cre = re.compile(srcpatt)
with open('myfile.txt', 'r') as file:
content = file.read()
wordlist = re.findall(r'(\d+O|O\d+)',str(content))
print(wordlist)
for word in wordlist:
subcontent = cre.sub(rplpatt, word)
newrep = re.compile(word)
newcontent = newrep.sub(subcontent,content)
with open('myfile.txt', 'w') as file:
file.write(newcontent)
print('"',srcpatt,'" is successfully replaced by "',rplpatt,'"')