[英]Find and replace full words only?
我对 Python 完全陌生,我目前正在尝试编写一个小脚本,用于在文件夹中相同类型的所有文件中查找和替换不同的输入。 它目前看起来像这样并且到目前为止有效:
import glob
import os
z = input('filetype? (i.e. *.txt): ')
x = input('search for?: ')
y = input('replace with?: ')
replacements = {x:y}
lines = []
for filename in glob.glob(z):
with open(filename, 'r') as infile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
lines.append(line)
with open(filename, 'w') as outfile:
for line in lines:
outfile.write(line)
lines = []
我的问题是我只想替换完整的单词,所以当尝试用 'x' 替换 '0' 时,'4025' 不应该变成 '4x25'。 我试图合并正则表达式,但我无法让它工作。
代替
line.replace(src, target)
尝试
re.sub(r'\b' + re.escape(src) + r'\b', target, line)
导入re
。 \\b
匹配一个词边界。
只需使用正则表达式 ( re
) 并在表达式中添加^
和$
模式。
line = re.sub('^'+src+'$', target, line)
不要忘记import re
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.