我有一个任务,使用python在文本文件中将“ O”(大写O)替换为“ 0”。但是一个条件是,我必须保留Over,NATO等其他词语。我只需要替换9OO至900、2OO6至2006等。我尝试了很多,但没有成功。我的代码如下。请任何人帮助我。提前致谢import resrcpatt = '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,'"')
3 回答

白板的微信
TA贡献1883条经验 获得超3个赞
import re
srcpatt = 'O'
rplpatt = '0'
cre = re.compile(srcpatt)
reg = r'\b(\d*)O(O*\d*)\b'
with open('input', 'r') as f:
for line in f:
while re.match(reg,line): line=re.sub(reg, r'\g<1>0\2', line)
print line
print('"',srcpatt,'" is successfully replaced by "',rplpatt,'"')

慕无忌1623718
TA贡献1744条经验 获得超4个赞
您可能只需要匹配前导数字后跟即可逃脱O
。这将无法处理OO7
,但是8080
例如可以很好地工作。这里没有哪个答案与尾随数字匹配。如果要这样做,则需要使用前瞻匹配。
re.sub(r'(\d)(O+)', lambda m: m.groups()[0] + '0'*len(m.groups()[1]), content)
添加回答
举报
0/150
提交
取消