Return the position of a word in a string

1

Can anyone help me with this question?

def fileRead(file):
        txt = open(file)
        print(txt.read())

def index(filepath, keywords):
    with open(filepath) as f:
        for lineno, line in enumerate(f, start=1):
            matches = [k for k in keywords if k in line]
            if matches:
                result = "{:<15} {}".format(','.join(matches), lineno)
                print(result)

#Programa Principal
fileRead('cores.txt')
fileRead('carta.txt')
index('cores.txt', ["amarelo"])
index('carta.txt', ["azul"])
index('carta.txt', ["verde"])
    
asked by anonymous 21.09.2016 / 22:46

1 answer

1

In your code, the word and line number is already returned, to also return the position of the word on the line, use str.index :

pos = line.split().index(keyword)

str.split will separate the line into pieces (separated by space) and with str.index get the position of the word. Here's an example:

s = 'foo bar baz'
i = s.split().index('bar') + 1

print ('bar é a {} palavra de {}'.format(i, s))
# bar é a 2 palavra de foo bar baz

In your code do so:

def index(filepath, keywords):
    output = "Keyword: {}, Line: {}, Index: {}"

    with open(filepath) as f:
        for lineno, line in enumerate(f, start = 1):
            line = line.rstrip()

            for keyword in keywords:
                if keyword in line:
                    pos = line.split().index(keyword) + 1

                    result = output.format(keyword, lineno, pos)
                    print (result)

index('cores.txt', ['amarelo'])

Assuming the file cores.txt has the following content:

verde
vermelho
amarelo
cinza amarelo
azul

The result will be:

Keyword: amarelo, Line: 3, Index: 1
Keyword: amarelo, Line: 4, Index: 2
    
23.09.2016 / 22:16