How can I find where a word is located in a sentence using python? For example the fourth word in the sentence.
sentence = "It's a beautiful world."
word = "world"
locate_word(word,sentence) = 4
You'll have to specify how you would like to split the sentence. I found a example from another answer. You can modify this to suit your need.
import re
sentence = "It's a beautiful world."
word = "world"
def locate_word(word, sentence):
# https://stackoverflow.com/a/6181784/12565014
wordList = re.sub("[^\w]", " ", sentence).split()
return wordList.index(word)
locate_word(word,sentence) # output 4
I believe this is a rather straightforward solution and easy to read;
sentence = "It's a beautiful world. Worldwide in the world, for the world"
word = "world"
ax = sentence.split(' ')
import re
for i in ax:
if len(re.findall('\\world\\b',i)) > 0:
print(ax.index(i))
Output:
3
7
10
For the above example it will work
import re
sentence = "It's a beautiful world."
word = "world"
lst = sentence.split()
for i in range(0,len(lst)):
if "." in lst[i]:
lst[i] = lst[i].replace(".", "")
print(lst.index(word))
Split the sentence(by default its splitting by spaces) then loop through the list that you got. If your word is in the list item it will give you back the index of it. And after this you add +1 to the index you've got because the countiong of lists starts from 0.
import string
def locate_word(word, sentence):
splitted = sentence.split()
indexes = []
for x in splitted:
if word in x and len(word) == len(x.strip(string.punctuation)):
indexes.append(splitted.index(x) + 1)
return print(indexes)
locate_word('worldwide', "It's a worldwide beautiful world. worldwide")
world
is included in the string, for example worldwide
as @Reznik pointed.
Dec 19, 2019 at 13:20
You can split the sentence at space, then lookup the word in the list.
Edit: based on the comment, you may also need to strip the punctuation.
import string
def locate_word(word, sentence):
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
ListOfWord = sentence.split(" ")
return ListOfWord.index(word)
sentence.split()
will give you["It's", 'a', 'beautiful', 'world.']
and"world."
is not the same as"world"
. So you might want to remove punctuation from the string (sentence = sentence.translate(str.maketrans('', '', string.punctuation))
) but that will change"It's"
to"Its"
too.