2013-04-03 122 views
3

我刚开始学习Python的2天前,对不起,如果我取得了明显的错误分割字符串用星号蟒蛇

strings: "brake break at * time" --> ["at","time"] 
"strang strange I felt very *" --> ["very",""] 

我想之前得到的字和后*

我尝试:

re.match(r"(?P(first_word)\w+) ('_*_') (?P(first_word)\w+)",strings).group('first_word') 

为获得第一个字

re.match(r"(?P(first_word)\w+) ('_*_') (?P(first_word)\w+)",strings).group('last_word') 

为获得最后的话

错误:没有重复

+0

你试过'。 split('*')',因为它是一个你不想要的'*' – avasal

回答

1

只需使用string.split('*')

这样的(适用于1只*):

>>> s = "brake break at * time" 
>>> def my_func(s): 
    parts = s.split('*') 
    a = parts[0].split()[-1] 
    b = parts[1].split()[0] if parts[1].split() else '' 
    return a,b 
>>> my_func(s) 
('at', ' time') 

或者,如果你想正则表达式:

>>> s = "brake break at * time 123 * blah" 
>>> regex = re.compile("(\w+)\s+\*\s*(\w*)") 
# Run findall 
>>> regex.findall(s) 
[(u'at', u'time'), (u'123', u'blah')] 
+1

是的输出正是我想要的!太感谢了! –

+0

它对这个例子不起作用''stra怪我觉得很*' - > [“very”,“”“]' – ovgolovin

+0

你的第一个例子不适用于's = ' – jamylak

1

尝试:

[x.strip() for x in "test1 * test2".split('*', 1)] 

.strip()摆脱掉空格和.split('*', 1)由星号分割字符串一次。

当你想只有一个字:

words = [x.strip() for x in "test1 * test2".split('*', 1)] 
first = words[0].rsplit(' ', 1)[1] 
last = words[1].split(' ', 1)[0] 
+0

这不会实现lly为例 – jamylak

+0

这是真的,谢谢你,改进了答案。 –

+0

虽然它没有给出确切的输出,但感谢您的帮助! –

2
import re 
text1 = "brake break at * time" 
text2 = "strang strange I felt very *" 
compiled = re.compile(r''' 
(\w+) # one or more characters from [_0-9a-zA-Z] saved in group 1 
\s+ # one or more spaces 
\* # literal * 
\s* # zero or more spaces 
(\w*) # zero or more characters from [_0-9a-zA-Z] saved in group 2 
''',re.VERBOSE) 

def parse(text): 
    result = compiled.search(text) 
    return [result.group(1), result.group(2)] 

print(parse(text1)) 
print(parse(text2)) 

输出:

['at', 'time'] 
['very', ''] 
+0

感谢您的全面解决方案! –

+0

恕我直言,这应该被标记为接受答案,它确实需要它。 –