k.davies
k.davies

Reputation: 3

Finding the first instance of words in python

I've been coding a program to find the first instance of each unique word in a sentence but my code doesn't work. I've tried to find a solution but I can't seem to be able to find one. Any help will be greatly appreciated.

csentence= input("Please enter a sentance, ") 
split_sentence=sentence.split
words=[ ]

for x, y in enumerate(words,1):
    if split_sentence .count(y)>1:
        words.append(sentence_split.index(y+1))
    else:
        words.append(x+1)

print(words)

Upvotes: 0

Views: 219

Answers (4)

hfz
hfz

Reputation: 421

csentence= input("Please enter a sentence, ") 
split_sentence=csentence.split() # added brackets & changed sentence to csentence
word_index=[]
words=[]
for x,y in enumerate(split_sentence):   
    print(x,y)   
    if y not in words:
        words.append(y)        
        word_index.append(x)

print(word_index)

Upvotes: 0

Nick is tired
Nick is tired

Reputation: 7056

The first step is to split the words into a list:

words = sentence.split()

Then you can use a dictionary to store the first occurrence of each word:

word_occurrences = {}
for word in words:
    word_occurrences[word] = words.index(word)

With:

sentence = "hi there hi to you there hi"

this results in:

word_occurrences = {'hi': 0, 'you': 4, 'to': 3, 'there': 1}

This can be tidied into a dictionary comprehension using:

words = sentence.split()    
word_occurrences = {word:words.index(word) for word in words}

Upvotes: 0

Tagc
Tagc

Reputation: 9072

Does this meet your requirements?

def get_word_positions(sentence):
    words = sentence.split()
    uniques = set(words)

    for word in uniques:
        yield word, words.index(word)

if __name__ == '__main__':
    sentence = input('Please enter a sentence: ')
    print(list(get_word_positions(sentence)))

Example Run

Please enter a sentence: The fox is a silly fox indeed a
[('The', 0), ('a', 3), ('is', 2), ('indeed', 6), ('silly', 4), ('fox', 1)]

Upvotes: 1

Glostas
Glostas

Reputation: 1190

split is a function. Therefore, you need to use split()

Upvotes: 0

Related Questions