2010-10-07 57 views
3

如何抓取圆括号内的元素并将其放入文件中?抓取圆括号内的元素

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

由于提前, 阿迪亚

+0

阿迪亚,请通过创建一个答案作出评论避免。在50代表,你可以留下这样的实际评论。谢谢! – Will 2010-10-08 19:17:29

回答

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

只需几个简单的字符串操作会做

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