N
N
Nazarius2020-08-09 21:41:55
Python
Nazarius, 2020-08-09 21:41:55

How to find the index of a word in a string if they are repeated?

Line example:

TEXT = """
The Zen of Python, by Tim Peters
1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
"""


Final output example:
TEXT_WORDS = [
        ('the', 1), ('zen', 5), ('of', 9), ('python', 12), ('by', 20),
        ('tim', 23), ('peters', 27), ('beautiful', 37), ('is', 47),
        ('better', 50), ('than', 57), ('ugly', 62), ('explicit', 71),
        ('is', 80), ('better', 83), ('than', 90), ('implicit', 95),
        ('simple', 108), ('is', 115), ('better', 118), ('than', 125),
        ('complex', 130), ('complex', 142), ('is', 150), ('better', 153),
        ('than', 160), ('complicated', 165),
    ]

I did it through tuples and the index() method, but if there are repetitions, then output ('is', 47) and so on 4 times (because the word "is" occurs in text 4)
An example of my code:
TEXT_WORDS = []
    for word in TEXT.split():
        r = (word, TEXT.index(word))
        TEXT_WORDS.append(r)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-08-09
@Nazarius

The second parameter of the index method allows you to specify from which position the search should start. Specify the last result + the length of the last word:

TEXT_WORDS = []
index = 0
for word in TEXT.split():
  index = TEXT.index(word, index)
  TEXT_WORDS.append((word, index))
  index += len(word)

I
IDzone-x, 2020-08-10
@IDzone-x

def get_indices(lst, el):
    return [i for i in range(len(lst)) if lst[i] == el]
    
    
print(get_indices([1, 5, 5, 2, 7], 7))

Note that this code returns the indices of all occurrences of the second argument. I think you can remake the evolution to fit your needs).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question