检查句型并替换为python中的单词
我试着读一个句子,检查句子中的每个单词是否有撇号,如果有,替换掉,否则继续。我已经在检查句型并替换为python中的单词,python,Python,我试着读一个句子,检查句子中的每个单词是否有撇号,如果有,替换掉,否则继续。我已经在dict中定义了撇号。dict的键具有模式,值具有替换模式的实际值。我尝试了以下代码 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", "
dict
中定义了撇号。dict的键
具有模式,值
具有替换模式的实际值。我尝试了以下代码
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)无需拆分单词并循环:
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
(请注意,这是Python2.7)除了“它不工作”之外,问题到底是什么?听起来像是试图转义字符串以插入数据库。如果这一点非常接近(不确定为什么还有撇号),那么这种方法是有缺陷的。不要这样做。除了“它不工作”之外,到底是什么问题?听起来好像你在试图转义字符串以插入数据库。如果这一点非常接近(不确定为什么还有撇号),那么这种方法是有缺陷的。不要这样做。如果字典中的值与键(如彼此的子字符串)重叠,这将是一个问题。虽然在原始代码中也会出现同样的问题。它应该适用于这个特定的dict。如果字典中的值与键(如彼此的子字符串)重叠,这将是一个问题。虽然在原始代码中也会出现同样的问题。它应该适用于这个特定的指令。