繁体   English   中英

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

[英]How to replace a character in some specific word in a text file using 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,'"')

re.sub可以接受替换功能,因此我们可以很好地削减它:

import re
with open('myfile.txt', 'r') as file:
    content = file.read()
with open('myfile.txt', 'w') as file:
    file.write(re.sub(r'\d+[\dO]+|[\dO]+\d+', lambda m: m.group().replace('O', '0'), content))

您可能只需要匹配前导数字后跟O就可以逃脱。 这不会处理OO7 ,但是例如可以与8080很好地配合使用。 这里没有哪个答案与尾随数字匹配。 如果要这样做,则需要使用前瞻匹配。

re.sub(r'(\d)(O+)', lambda m: m.groups()[0] + '0'*len(m.groups()[1]), content)
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,'"')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM