使用:
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),然后您只需将单词的长度添加到其中,即可获得其结尾的索引。
如果使用position表示句子中的第n个单词,则可以执行以下操作:
这将在每次出现空格后拆分句子,并将句子保存在列表中(按单词顺序)。如果句子包含关键字,list.index()将找到它的位置。
编辑:
if语句是确保关键字在语句中所必需的,否则list.index()将引发ValueError。
相关问题 更多 >
编程相关推荐