如何使用python替换文本文件中某些特定单词的字符

我有一个任务,使用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,'"')


慕妹3242003
浏览 422回答 3
3回答

白板的微信

import resrcpatt = 'O'rplpatt = '0'cre = re.compile(srcpatt)reg = r'\b(\d*)O(O*\d*)\b'with open('input', 'r') as f:&nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; while re.match(reg,line): line=re.sub(reg, r'\g<1>0\2', line)&nbsp; &nbsp; &nbsp; &nbsp; print lineprint('"',srcpatt,'" is successfully replaced by "',rplpatt,'"')

慕无忌1623718

您可能只需要匹配前导数字后跟即可逃脱O。这将无法处理OO7,但是8080例如可以很好地工作。这里没有哪个答案与尾随数字匹配。如果要这样做,则需要使用前瞻匹配。re.sub(r'(\d)(O+)',&nbsp;lambda&nbsp;m:&nbsp;m.groups()[0]&nbsp;+&nbsp;'0'*len(m.groups()[1]),&nbsp;content)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python