2

How to get Python to return the position of a repeating word in a string?

E.g. the word "cat" in "the cat sat on the mat which was below the cat" is in the 2nd and 11th position in the sentence.

  • Possible duplicate of [How to find all occurrences of an element in a list?](http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – wpercy Feb 04 '16 at 19:10
  • `string.index` returns the first occurrence of a substring in a string. You're also using a for loop that goes from 0 to the length of the sentence _in characters_, not _words_. – Davis Yoshida Feb 04 '16 at 19:10
  • Since it's not quite clear from your code, what task are you trying to accomplish? – Davis Yoshida Feb 04 '16 at 19:11
  • `[i for i, x in enumerate(s) if s.count(x) > 1]` – Maroun Feb 04 '16 at 19:11
  • @MarounMaroun that will give repeated characters, and do so in O(n^2) ew. – Adam Smith Feb 04 '16 at 19:33

6 Answers6

3

You can use re.finditer to find all occurrences of the word in a string and starting indexes:

import re

for word in set(sentence.split()):
    indexes = [w.start() for w in re.finditer(word, sentence)]
    print(word, len(indexes), indexes)

And using dictionary comprehension:

{word: [w.start() for w in re.finditer(word, sentence)] for word in sentence.split()}
midori
  • 4,807
  • 5
  • 34
  • 62
1

This will return a dictionary mapping each word in the sentence, which repeates at least once, to the list of word index (not character index)

from collections import defaultdict

sentence = "the cat sat on the mat which was below the cat"

def foo(mystr):
    sentence = mystr.lower().split()
    counter = defaultdict(list)
    for i in range(len(sentence)):
        counter[sentence[i]].append(i+1)

    new_dict = {}
    for k, v in counter.iteritems():
        if len(v) > 1:
            new_dict[k] = v

    return new_dict

print foo(sentence)
Fanchi
  • 757
  • 8
  • 23
0

The following will take an input sentence, take a word from the sentence, and then print the position(s) of the word in a list with a starting index of 1 (it looks like that's what you want from your code).

sentence = input("Enter a sentence, ").lower()
word = input("Enter a word from the sentence, ").lower()
words = sentence.split(' ')
positions = [ i+1 for i,w in enumerate(words) if w == word ]
print(positions)
wpercy
  • 9,636
  • 4
  • 33
  • 45
0

I prefer simplicity and here is my code below:

sentence = input("Enter a sentence, ").lower()
word_to_find = input("Enter a word from the sentence, ").lower()
words = sentence.split()  ## Splits the string 'sentence' and returns a list of words in it. Split() method splits on default delimiters.

for pos in range(len(words)):
    if word_to_find == words[pos]:   ## words[pos] corresponds to the word present in the 'words' list at 'pos' index position.
        print (pos+1)

The 'words' consists of the list of all the words present in the sentence. Then after that, we iterate and match each word present at index 'pos' with the word we are looking to find(word_to_find) and if both the words are same then we print the value of pos with 1 added to it.

Hope this is simple enough for you to understand and it serves your purpose.

If you wish to use a list comprehension for the above, then:

words = sentence.split()
positions = [ i+1 for i in range(len(words)) if word_to_find == words[i]]
print (positions)

Both the above ways are same, just the later gives you a list.

Archit
  • 976
  • 16
  • 28
0
positions= [] 

sentence= input("Enter the sentence please: ").lower() 

sentence=sentence.split( ) 

length=len(sentence))

word = input("Enter the word that you would like to search for please: ").lower() 

if word not in sentence: 
     print ("Error, '"+word+"' is not in this sentence.") 

else: 
     for x in range(0,length):
          if sentence[x]==word: #
               positions.append(x+1)
     print(word,"is at positions", positions)
Tom Fuller
  • 5,291
  • 7
  • 33
  • 42
-1
s="hello fattie i'm a fattie too"
#this code is unsure but manageable
looking word= "fattie"
li=[]
for i in range(len(s)):
    if s.startswith(lw, i):
        print (i)
        space = s[:i].count(" ")
        hello = space+1
        print (hello)
        li.append(hello)
print(li)
Cœur
  • 37,241
  • 25
  • 195
  • 267
sophie
  • 1