我有一个任务,使用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,'"')
白板的微信
慕无忌1623718
相关分类