H
H
hey_umbrella2021-11-13 02:20:08
Python
hey_umbrella, 2021-11-13 02:20:08

How to iterate over one word in each line?

elif '<math-input-answer>' in answer_row['content']:
            correct= answer_row['content'].partition('<math-input-answer>')[2].partition('</math-input-answer>')[0]
            print(correct)


I use this code to get values ​​from this text that are inside the math-input-answer tag, but now it only gets the first x + y value, and does not go further, how to put it in a loop?
<p><vim-math id="m7859635math1">AB+CD=|</vim-math><math-input id="m7859635MI1" keyboard-skin="junior" keyboard-type="base" strict-check="false">
  <math-input-answer>x+y</math-input-answer>
  <math-input-answer>y+x</math-input-answer>
</math-input><vim-math id="m7859635math2">|+|</vim-math><math-input id="m7859635MI2" keyboard-skin="junior" keyboard-type="base" strict-check="false">
  <math-input-answer>t+z</math-input-answer>
  <math-input-answer>z+t</math-input-answer>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-11-13
@hey_umbrella

data = '''<p><vim-math id="m7859635math1">AB+CD=|</vim-math><math-input id="m7859635MI1" keyboard-skin="junior" keyboard-type="base" strict-check="false">
  <math-input-answer>x+y</math-input-answer>
  <math-input-answer>y+x</math-input-answer>
</math-input><vim-math id="m7859635math2">|+|</vim-math><math-input id="m7859635MI2" keyboard-skin="junior" keyboard-type="base" strict-check="false">
  <math-input-answer>t+z</math-input-answer>
  <math-input-answer>z+t</math-input-answer>'''
  
string = '<math-input-answer>'
results =[]
 
def get_text(line):
    line = line.split('>')[1]
    line = line.split('<')[0]
    return line
     
for line in data.splitlines():
    if string in line:
        result = get_text(line)
        results.append(result)
print(results)

Here I wrote a completely ugly parsing function, because I'm too lazy to screw bs4 or something like that, for example, stuck on the phone, or compose regex ...
instead of it, you can substitute a more different one at your discretion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question