[英]Finding the position of a word in a string
With: 附:
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
I want to find the position of the keyword in the sentence. 我想在句子中找到关键字的位置。 So far, I have this code which gets rid of the punctuation and makes all letters lowercase: 到目前为止,我有这个代码摆脱标点符号并使所有字母小写:
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)
I know need a piece of code which actually finds the position of the word. 我知道需要一段实际找到该单词位置的代码。
This is what str.find()
is for : 这就是str.find()
的用途:
sentence.find(word)
This will give you the start position of the word (if it exists, otherwise -1), then you can just add the length of the word to it in order to get the index of its end. 这将为您提供单词的起始位置(如果存在,否则为-1),然后您可以将单词的长度添加到其中以获得其结尾的索引。
start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1
If with position you mean the nth word in the sentence, you can do the following: 如果您的位置是指句子中的第n个单词,您可以执行以下操作:
words = sentence.split(' ')
if keyword in words:
pos = words.index(keyword)
This will split the sentence after each occurence of a space and save the sentence in a list (word-wise). 这将在每次出现空格后分割句子并将句子保存在列表中(逐字)。 If the sentence contains the keyword, list.index() will find its position. 如果句子包含关键字, list.index()将找到它的位置。
EDIT : 编辑 :
The if statement is necessary to make sure the keyword is in the sentence, otherwise list.index() will raise a ValueError. if语句是确保关键字在句子中所必需的,否则list.index()将引发ValueError。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.