python正则表达式Variab

2024-10-16 20:44:23 发布

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

我正在尝试使用查找表替换文本文件中的值

查找表的格式如下

Search             Replace
Unit Of Measure    Unit of Measure
Bill Of Material   Bill of Material
Reference Item     Reference Material Number

我正在使用re.sub(Search, Replace, File)

我需要为每个迭代执行(r'\b Unit Of Measure\b', Replace, File)之类的操作。你知道吗

我无法将这些标记放入变量中。你知道吗

你能帮忙吗?你知道吗

下面是代码

import re
f1 = open('C:\Scripts\FNR\SearchReplacekey.txt','r')
f = open("C:\Scripts\FNR\log.txt",'a')
f.seek(0)
f.truncate()
f.close()
for line in f1:
    fields = line.split('|')
    a = fields[0]
    Srch = fields[1]
    Repl = fields[2]
    f = open("C:\Scripts\FNR\Output.txt",'r')
    filedata = f.read()
    check = re.search(Srch,filedata)
    f.close()

    if check == -1:

        f = open("C:\Scripts\FNR\log.txt",'a')
        newdata = a + ' ' + Srch + ' ' + Repl
        f.write(newdata + "\n")
        f.close()
    else:

        # the problem is here I need to force Srch to match exact word
        newdata = re.sub(Srch,Repl,filedata)

        f = open("C:\Scripts\FNR\Output.txt",'w')
        f.write(newdata)
        f.close()

谢谢你, 科西克


Tags: ofretxtfieldsclosescriptsunitopen
2条回答
>>>searchPattern = "Unit Of Measure"
>>>replacePatter = "Unit of Measure"
>>>sampleString = "not Unit Of measure, but Unit Of Measure and not Unit Of"
>>>re.sub(searchPattern,replacePatter, sampleString)
'not Unit Of measure, but Unit of Measure and not Unit Of'

也许我在这里遗漏了一些东西,但是如果你用引号把这些模式括起来,这似乎就足够了。你知道吗

我不知道你在问什么,但可能是:

searchs = ["Unit Of Measure", "Bill Of Material"]
for s in searchs:
  re.sub(s, Replace, File)

相关问题 更多 >