抓住括号内的元素

时间:2010-10-07 14:02:18

标签: python regex

如何抓取括号内的元素并将它们放在文件中?

我(我) 你(你) 他(他) 她(她)

提前致谢, 埃迪雅

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

你签出了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

输出:

I
You
He
She

答案 2 :(得分:1)

只需进行一些简单的字符串操作

>>> 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