在字符串中查找单词的位置

17

使用:

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")

我想要找到句子中关键词的位置。目前,我已经有了这段代码,它可以去除标点符号并将所有字母转换为小写:

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''#This code defines punctuation
#This code removes the punctuation
no_punct = "" 
for char in sentence:
   if char not in punctuations:
       no_punct = no_punct + char

no_punct1 =(str.lower (no_punct)

我需要一段代码来实际查找单词的位置。


1
顺便提一下,您不需要定义自己的 punctuations 字符串:它已经在 string.punctuation 中定义了,还有其他有用的字符子集。但是,您可能不需要从句子中去除标点符号,但您可能想从关键字中去除它。顺便说一下,调用方法的通常方式是像 no_punct.lower() 而不是 str.lower(no_punct) - PM 2Ring
2个回答

34

这就是str.find()的用途:

sentence.find(word)

这将给出单词的起始位置(如果存在,否则为-1),然后您可以只需添加单词长度以获取其末尾的索引。

start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1

如果单词出现多次,这个会起作用吗? - Coddy

4
如果您所说的“位置”是指句子中的第n个单词,您可以按照以下步骤操作:
words = sentence.split(' ')
if keyword in words:
    pos = words.index(keyword)

这将在每次出现空格后分割句子,并将句子以列表形式保存(按单词)。如果句子包含关键字,list.index() 将查找其位置。 编辑: if语句是必要的,以确保关键字在句子中,否则list.index()会引发ValueError异常。

如果这个单词在句子的结尾并且后面跟着一个句号,那么会出现问题。 - Coddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接