I am looking to remove the last statement in a rule used for parsing. The statements are encapsulated with @
characters, and the rule itself is encapsulated with pattern tags.
What I want to do is just remove the last rule statement.
My current idea to achieve this goes like this:
- Opens the rules file, saves each line as an element into a list.
- Selects the line that contains the correct rule-id and then saves the rule pattern as a new string.
- Reverses the saved rule pattern.
- Removes the last rule statement.
- Re-reverses the rule pattern.
- Adds in the trailing pattern tag.
So the input will look like:
<pattern>@this is a statement@ @this is also a statement@</pattern>
Output will look like:
<pattern>@this is a statement@ </pattern>
My current attempt goes like this:
with open(rules) as f:
lines = f.readlines()
string = ""
for line in lines:
if ruleid in line:
position = lines.index(line)
string = lines[position + 2] # the rule pattern will be two lines down
# from where the rule-id is located, hence
# the position + 2
def reversed_string(a_string): #reverses the string
return a_string[::-1]
def remove_at(x): #removes everything until the @ character
return re.sub('^.*?@','',x)
print(reversed_string(remove_at(remove_at(reversed_string(string)))))
This will reverse the string but not remove the last rule statement once it has been reversed.
Running just the reversed_string()
function will successfully reverse the string, but trying to run that same string through the remove_at()
function will not work at all.
But, if you manually create the input string (to the same rule pattern), and forgo opening and grabbing the rule pattern, it will successfully remove the trailing rule statement.
The successful code looks like this:
string = '<pattern>@this is a statement@ @this is also a statement@</pattern>'
def reversed_string(a_string): #reverses the string
return a_string[::-1]
def remove_at(x): #removes everything until the @ character
return re.sub('^.*?@','',x)
print(reversed_string(remove_at(remove_at(reversed_string(string)))))
As well, how would I add in the pattern tag after the removal is complete?