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.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1. Parameters: sub: Substring that needs to be searched in the given string.
Get position of a character in String using find() method In this technique, to get the position of a character in a string in Python we will use the find() method. It is a built in method of string class, which takes a character whose position needs to be found out as a parameter.
The INSTR function searches a character string for a specified substring, and returns the character position in that string where an occurrence of that a substring ends, based on a count of substring occurrences.
This is what str.find()
is for :
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.
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:
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.
EDIT:
The if statement is necessary to make sure the keyword is in the sentence, otherwise list.index() will raise a ValueError.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With