我试图阅读一个句子,并且对于句子中的每个单词,检查单词是否存在某些撇号,并且如果它们存在,则替换它们继续。我在dict
中定义了我的撇号。 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
答案 0 :(得分:4)
无需分割单词并循环遍历它们:
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)