3

我2天前刚开始学习python,如果我犯了明显的错误,请见谅

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

为了得到最后一句话

错误:没有什么可重复的

4

3 回答 3

2

只需使用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')]
于 2013-04-03T09:31:21.820 回答
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', '']
于 2013-04-03T09:36:02.853 回答
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]
于 2013-04-03T09:27:21.283 回答