Capturing items in parentheses

How can I grab items in parentheses and put them in a file?

me (I) you (you) he (he) her (she)

Thanks in advance, Adia

+3
source share
3 answers
import re

txt = 'me (I) you (You) him (He) her (She)'
words = re.findall('\((.+?)\)', txt)

# words returns: ['I', 'You', 'He', 'She']
with open('filename.txt', 'w') as out:
    out.write('\n'.join(words))

# file 'filename.txt' contains now:

I
You
He
She
+5
source

Have you checked pyparsing ?

from pyparsing import Word, alphas

text = "me (I) you (You) him (He) her (She)"

parser = "(" + Word(alphas).setResultsName("value") + ")"

out = open("myfile.txt", "w")
for token, start, end in parser.scanString(text):
    print >>out, token.value

Conclusion:

I
You
He
She
+2
source

Only a few simple string manipulations will do

>>> s="me (I) you (You) him (He) her (She)"
>>> for i in s.split(")"):
...     if "(" in i:
...        print i.split("(")[-1]
...
I
You
He
She
+1
source

Source: https://habr.com/ru/post/1768420/


All Articles