Python - Finding word on same line as given input

266 Views Asked by At

For a method I'm creating, I want to take in a word that is found on the end of a line, and I then want to append the word found to the left of it (at the start of the line up to a space character) to an array.

Here is my code so far:

def ruleElements(factor):
    # Creates list of RHS and LHS rule elements
    results = []

    # If RHS factor is found in grammar, append corresponding LHS.
    for line in grammarFile:
        start = line.find(0)
        end = line.find(' ', start)
        if factor in line:
            results.append(line[start:end])

    return results

So far the outputted array comes up empty all the time. Not sure where my logic is wrong.

A line in the grammarFile looks like, for example:

VP -> V NP

NP -> N

VP -> V PP

I want to take the part on the right-side of -> as an input and append the left-side to an array to be used in other parts of the program.

2

There are 2 best solutions below

1
Carlos Mermingas On BEST ANSWER

An idea...

You can split the lines by the '->' delimiter and trim spaces:

line_items = [x.strip() for x in line.split('->')]

# Splits 'VP -> V PP' into ['VP', 'V PP']

Then you can look up your input factor in the second item of this array and return the first item with something like this:

for line in grammarFile:
    line_items = [x.strip() for x in line.split('->')]
    if factor == line_items[1]:
        return line_items[0:1]

I am not sure what grammarFile is exactly (bytes? strings?) but something like this could work.

I hope this helps.

2
zenlc2000 On

Split the line on spaces. This gives you a list of words in the order they appear. list[-1] is the last word, list[-2] is the word to the left of it.

myStr = 'My dog has fleas'
words = myStr.split(' ')
print(words[-1], words[-2])

fleas
dog