0

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.

Curtis White
  • 250
  • 3
  • 13

2 Answers2

0

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
zenlc2000
  • 451
  • 4
  • 9
  • You mean like: for line.split(' ') in grammarFile: if factor == list[-1] results.append(list[-2]) – Curtis White Nov 06 '16 at 17:54
  • Thanks. This is useful, but I don't think the results will consistently get me what I need for my question, but I'll definitely keep this in mind. – Curtis White Nov 07 '16 at 03:10
0

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.

Carlos Mermingas
  • 3,822
  • 2
  • 21
  • 40