[英]Python - Finding word on same line as given input
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: grammarFile中的一行如下所示:
VP -> V NP 副总裁-> V NP
NP -> N NP-> N
VP -> V PP 副总裁-> 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. 我想将->右侧的部分作为输入,并将左侧附加到要在程序其他部分中使用的数组。
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. list [-1]是最后一个单词,list [-2]是它左边的单词。
myStr = 'My dog has fleas'
words = myStr.split(' ')
print(words[-1], words[-2])
fleas
dog
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: 然后,您可以在此数组的第二项中查找输入factor
,并使用以下内容返回第一项:
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. 我不确定grammarFile到底是什么(字节?字符串?),但是类似的东西可能起作用。
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.