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

2024-04-25 23:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

使用:

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)

我知道需要一段代码来找到单词的位置。


Tags: theno代码ininputcodethiskeyword
2条回答

这就是^{}的用途:

sentence.find(word)

这将为您提供单词的起始位置(如果它存在,则为-1),然后您只需将单词的长度添加到其中,即可获得其结尾的索引。

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

如果使用position表示句子中的第n个单词,则可以执行以下操作:

words = sentence.split(' ')
if keyword in words:
    pos = words.index(keyword)

这将在每次出现空格后拆分句子,并将句子保存在列表中(按单词顺序)。如果句子包含关键字,list.index()将找到它的位置。

编辑

if语句是确保关键字在语句中所必需的,否则list.index()将引发ValueError。

相关问题 更多 >