【发布时间】:2019-12-19 21:42:32
【问题描述】:
如何使用python找到一个单词在句子中的位置? 例如句子中的第四个单词。
sentence = "It's a beautiful world."
word = "world"
locate_word(word,sentence) = 4
【问题讨论】:
-
问题是将句子拆分为单个单词。一个简单的
sentence.split()会给你["It's", 'a', 'beautiful', 'world.']和"world."与"world"不同。因此,您可能希望从字符串 (sentence = sentence.translate(str.maketrans('', '', string.punctuation))) 中删除标点符号,但这也会将"It's"更改为"Its"。