[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in 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.