用Python替换其他txt文件中的文件中的字符串

时间:2016-12-21 21:08:43

标签: python regex

我从replacing text in a file with Python

获得了此代码
VBComponent

但我无法从其他txt文件加载repldict。 我试过

import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
    return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
    for line in fin:
        fout.write(regex.sub(replfunc,line))

但它没有用。

2 个答案:

答案 0 :(得分:3)

如果字典文件具有以下简单格式:

zero 0
one 1
temp bob
garage nothing

您可以使用split(不是stripsplit创建字典,而参数在某种程度上具有集成的strip功能),在生成器理解中产生元组(键,值),传递给dict

repldict=dict(line.split() for line in open(os.path.join(syspath,"rules.txt"), 'r'))

结果:

{'temp': 'bob', 'one': '1', 'garage': 'nothing', 'zero': '0'}

答案 1 :(得分:1)

考虑到您的规则.txt'文件看起来像:

zero:0
one:1
temp:bob
garage:nothing

然后:

with open(syspath+'/rules.txt', 'r') as rules:
    repldict={}
    for line in rules:
        key, value = line.strip().split(':')
        repldict[key] = value