python正则表达式不工作

时间:2016-10-12 04:36:24

标签: python regex substitution

我正在通过Python自动化无聊的东西,并且在其中一个练习项目中遇到了问题。

在第8章中,有一个项目,您可以在其中创建一个程序,该程序读取txt文件,识别某些单词,提示替换,然后替换找到的单词。我出于某种原因遇到了替代问题,我无法弄清楚原因。

import re, os

# Convert text file to string
textString = open('C:\\Users\\me\\Desktop\\madlib.txt', 'r')
content = str(textString.read())
i = 2

while i == 2:
    #Search string for expressions ADJECTIVE, NOWN, ADVERB, and VERB.
    keyRegex = re.compile(r'ADJECTIVE|NOUN|ADVERB|^VERB')
    keyword = keyRegex.search(content)

    #Upon finding keyword, using if statements test the type of keyword
    if keyword.group() == 'ADJECTIVE':
        print('Please enter an adjective:')
        replacement = str(input())
        keyRegex.sub(replacement, content)
        print(content)
----snip----

所以我在第一部分中读取了文件,设置了一个while循环(继续循环并有办法结束它),然后开始搜索关键字。例如,如果它找到单词ADJECTIVE,则会提示输入形容词。然后我输入替换,这就是事情发生的地方。

字符串'内容'中的ADJECTIVE一词实际上没有被替换。这是为什么?

感谢您的回答。

1 个答案:

答案 0 :(得分:0)

re.sub()返回一个你没有存储的新字符串。与许多其他Python方法一样,如果要更改它,则需要将新结果存储在变量中。

content = keyRegex.sub(replacement, content)