python:使用variab替换精确匹配

2024-05-23 14:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

程序读取文本文件并基于变量替换匹配的单词。问题是非精确匹配正在被替换。所以如果我把“the”改成“da”,那么“then”就变成了“dan”

for fn in os.listdir('.'):
 if os.path.isfile(fn):
    if fn.endswith(".txt"):

        s = open(fn).read()

        for i in skills:
            link = skills[i]        

            s = s.replace(i, "<a href=\"%s\">%s</a>" %(link,i), 1)

        print "%s updated" %fn

        f = open(fn, 'w')
        f.write(s)
        f.close()

问题出在s = s.replace(i, "<a href=\"%s\">%s</a>" %(link,i), 1),其中s.replace()中的第一个参数是包含要匹配的字符串的变量。

我试过使用单词边界s = s.replace(r'\b'+i+r'\b', "<a href=\"%s\">%s</a>" %(link,i), 1)

i处的值格式化为一个新变量:regex = r'\b' + i + r'\b',并使用regex作为s.replace中的第一个参数,但它不起作用。

注意。skills是一个包含单词/链接对的字典


Tags: in程序for参数ifoslinkopen
3条回答

如果string是读取文件的内容:

string = string.replace('the ', 'da ') # space ensures then isn't replaced

当使用regex匹配要替换的字符时,需要使用^{}函数。string.replace函数不接受regex作为参数。

由于s是一个字符串,因此它不支持正则表达式操作。

要在字符串上使用正则表达式,需要显式地执行此操作。

所以在代码的开头

import re

你现在用的地方

s = s.replace(i, "<a href=\"%s\">%s</a>" %(link,i), 1)

取而代之的是

s = re.sub(r'\b'+i+r'\b', '<a href="%s">%s</a>'%(link,i), s, 1)

相关问题 更多 >