我想用python拆分字符串。我已经成功地为一个变量完成了它,但发现它很难为2做。
字符串:
Paragraph 4-2 says. i am going home$ early- Yes.
我需要输出
Paragraph 4-2 says
i am going home
early
Yes
句子应该从.
,$
和-
分开(但当它在2个数字(4-2)之间时,它不应该分开)< / p>
我该怎么做?
text.split('.')
更新
新输出应该是:
Paragraph 4-2 says.
i am going home$
early-
Yes.
答案 0 :(得分:5)
>>> import re
>>> s = 'Paragraph 4-2 says. i am going home$ early- Yes'
>>>
>>> re.split(r'(?<!\d)\s*[.$-]\s*(?!\d)', s)
['Paragraph 4-2 says', 'i am going home', 'early', 'Yes']
\s*[.$-]\s*
与.
,$
或-
中任意一个被0或更多空格(\s*
)包围的内容匹配。 (?<!\d)
是一个负面观察,以确保匹配前面没有数字。(?!\d)
是一个负向前瞻,以确保匹配后面没有数字。您可以阅读有关外观here的更多信息。
答案 1 :(得分:4)
>>> re.split('(?<=\D)[.$-](?=\D|$)', s)
['Paragraph 4-2 says', ' i am going home', ' early', ' Yes']
>>>
(?<\D)[.$-](?=\D)
将获得。$ - ,而不是由意外者跟随或继续。前瞻和后瞻不会消耗任何字符串。所以字符串只会被分割成。$ - ,而不包含数字。
修改强>
>>> re.findall('.*?(?<=\D)[.$-](?=[\D]|$)', s)
['Paragraph 4-2 says.', ' i am going home$', ' early-', ' Yes.']
答案 2 :(得分:1)
你可以这样做:
>>> import re
>>> st='Paragraph 4-2 says. i am going home$ early- Yes.'
>>> [m.group(1) for m in re.finditer(r'(.*?[.$\-])(?:\s+|$)',st)]
['Paragraph 4-2 says.', 'i am going home$', 'early-', 'Yes.']
如果你根本不打算修改匹配组(带条或其他东西),你也可以使用相同的正则表达式的findall:
>>> re.findall(r'(.*?[.$\-])(?:\s+|$)',st)
['Paragraph 4-2 says.', 'i am going home$', 'early-', 'Yes.']
正则表达式解释为here,但总结如下:
(.*?[.$\-]) is the capture group containing:
.*? Any character (except newline) 0 to infinite times [lazy]
[.$\-] Character class matching .$- one time
(?:\s+|$) Non-capturing Group containing:
\s+ First alternate: Whitespace [\t \r\n\f] 1 to infinite times [greedy]
| or
$ Second alternate: end of string
如果您不想将(.*?[.$\-])(?:[ ]+|$)
与\r\n\f
\s
,具体取决于您的字符串