在保持标点符号的同时替换字符串

时间:2018-02-02 17:14:08

标签: python-2.7

我有一个任务是编写一个程序来替换单词" corgi"等Noun,Place,PluralNoun等单词。我得到的代码90%正确,但我错过了标点符号,但我不知道为什么。这是我写的代码:

parts_of_speech  = ["PLACE", "PERSON", "PLURALNOUN", "NOUN"]

test_string = """This is PLACE, no NOUN named PERSON, We have so many PLURALNOUN around here."""

def word_in_pos(word, parts_of_speech):
    for pos in parts_of_speech:
        if pos in word:
            return word
    return None

def play_game(ml_string, parts_of_speech):   
    replaced =[]
    word=ml_string.split(" ")
    for w in word:
        print w
        con = word_in_pos(w,parts_of_speech)
        if con != None:
            replaced.append(w.replace(con,"corgi"))
        else:
            replaced.append(w)
    return " ".join(replaced)

print play_game(test_string, parts_of_speech)

1 个答案:

答案 0 :(得分:1)

word_in_pos()完整地返回参数word,包括其中的任何标点符号。因此,当您执行replace()时,您也会替换标点符号。相反,只需从pos返回word_in_pos()

def word_in_pos(word, parts_of_speech):
    for pos in parts_of_speech:
        if pos in word:
            return pos
    return None

结果:

  

这是corgi,没有corgi名为corgi,我们周围有很多小狗。