2012-05-12 91 views
2

我的语言是Python简单的regex麻烦

输入看起来像:

'0 0 0 0 1 0 0 0 1 1 0 0' 

等。

我想要的输出:

('0 0 0 0', '1 0 0 0', '1 1 0 0') 

或每一组4个数字的是它自己的元素

到目前为止,我已经把

>>> truth = re.compile('(([0-1]\D*?){4})*') 
>>> truth.search('0 0 0 0 1 0 0 0').groups() 
('0 0 0 0', '0') 

或和几个类似的事情,但没有什么比这更近了。这里有几件事对我来说是新的,我正在阅读文档,但似乎无法拼凑出什么东西分崩离析。值得注意的是,我现在不是为什么我得到最后的0 ...

输入最终会有许多行,但如果它适用于小案例我相信它会翻译。

感谢

+2

你必须用正则表达式来做这个吗?如果使用'.split()'和'.join()',可能会更简单。 –

+0

很多很好的答案,我没有想到要问的问题。你指出我没有必要使用正则表达式。 –

回答

6

我不会用正则表达式这一点。而是使用grouperrecipesitertools documentation

>>> [' '.join(x) for x in grouper(4, truth.split())] 

看到它联机工作:ideone


下面是grouper的源代码(由迭代工具文档复制):

from itertools import izip_longest 

def grouper(n, iterable, fillvalue=None): 
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return izip_longest(fillvalue=fillvalue, *args) 
1

你应该检查出list comprehension

>>> MyString = '0 0 0 0 1 0 0 0 1 1 0 0' 
>>> [MyString[x:x+7] for x in range(0,len(MyString),8)] 
>>> ['0 0 0 0', '1 0 0 0', '1 1 0 0'] 
+2

最好不要将变量命名为'string'模块 – jamylak

+0

好点,更改为标准的“MyX”格式。 – Josiah

3

我对Python不是很了解,但是你可以稍微改变一下你的正则表达式,并用re.findall()来代替。

re.findall('(?:[0-1]\s*){4}', '0 0 0 0 1 0 0 0 1 1 0 0') 
+0

+1如果它必须是一个正则表达式,这将起作用。 –

1

该做的:

>>> s='0 0 0 0 1 0 0 0 1 1 0 0' 
>>> [' '.join(x) for x in zip(*[iter(''.join(s.split()))]*4)] 
['0 0 0 0', '1 0 0 0', '1 1 0 0'] 

如果你想有一个元组:

>>> tuple(' '.join(x) for x in zip(*[iter(''.join(s.split()))]*4)) 
('0 0 0 0', '1 0 0 0', '1 1 0 0') 

如果你真的想要一个正则表达式:

>>> [x.strip() for x in re.findall(r'(?:\d\s*){4}',s)] 
['0 0 0 0', '1 0 0 0', '1 1 0 0'] 
0

一个疯狂的解决方案只是为了好玩:

import math 
s = '0 0 0 0 1 0 0 0 1 1 0 0' 
step = 8 
result = [s[0+i*step:step+i*step] for i in xrange(int(math.ceil(float(len(s))/step)))] 
print result