检查模式并替换句子python的单词



我正在尝试阅读一个句子,对于句子中的每个单词,请检查该单词是否存在某些撇号,如果它们存在,请替换它们,否则继续。我已经在dict中定义了我的撇号.字典的key具有模式,value具有替换模式的实际值。我尝试了以下代码

tweet = "you're his i'm couldn't can't won't it's"
apostrophes = {"'s":" is","'re":" are","'ll":" will","'d":" would","i'm":"I am","I'm":"I am","won't":"will not", "'ve":" have","can't":"cannot","couldn't":"could not"}
words = tweet.split()
for word in words:
    for k in apostrophes.keys():
       if k in word:
           word = word.replace(k,apostrophes.get(k))
       else:
           pass

无需拆分单词并循环访问它们:

tweet = "you're his i'm couldn't can't won't it's"
apostrophes = {"'s":" is","'re":" are","'ll":" will","'d":" would","i'm":"I am","I'm":"I am","won't":"will not", "'ve":" have","can't":"cannot","couldn't":"could not"}
for k, v in apostrophes.iteritems():
    tweet = tweet.replace(k, v)
print tweet # you are his I am could not cannot will not it is

(请注意,这是python 2.7)

最新更新