2016-08-16 102 views
0

我想替换文本文件中的字符串,以便它只替换字符串的完全匹配。Python替换后没有某些字符的字符串

因此,如果该文件是:

"word" 
"word_1" 
"word1" 
"wordA" 

我想只更换wordtest_1我这样做:

text.replace("word", "test_1") 

但是通过这样做,我也取代所有其他word与其他文字在该字符串之后。因此,该文件将是这样的:

"test_1" 
"test_1_1" 
"test_11" 
"test_1A" 

我想它,所以我只能更换word,使其只替换它,如果没有任何小写字母,大写字母或之后下划线。我希望替换仅限于完全匹配,因此如果文件中有其他字符串,并且其后的文字与字母,数字或下划线相同,则不会受到影响。我也希望如此,如果其他任何字符后,未字母,数字或下划线将被取代一样,如果它是:

word" 
word; 
word: 

这些将是很好的,因为他们没有字母,数字或后下划线他们。

我想这让我可以喜欢不同的东西取代其他字符串:

text.replace("word", "test_1") 
text.replace("word_1", "test_2") 
text.replace("word1", "test_3") 
text.replace("wordA", "test_4") 

因此该文件将是:

test_1 
test_2 
test_3 
test_4 

我将如何做到这一点?

+4

这听起来像是正则表达式的工作! – Max

+1

're.sub(r'\ bword \ b','test_1',text)'?请参阅http://ideone.com/uneywY –

+0

如果有人添加正则表达式标记,我将关闭http://stackoverflow.com/questions/15863066/python-regular-expression-match-whole-word –

回答

0

试试这个:

data = """word 
word_1 
word1 
wordA 
""" 

replacements = { 
    "word": "test_1", 
    "word_1": "test_2", 
    "word1": "test_3", 
    "wordA": "test_4" 
} 

print(reduce(lambda a, b: a.replace(*b), replacements.iteritems(), data))