![](/img/trans.png)
[英]find words with capital letter as starting letter but not preceded by space
[英]Pythonic sentence splitting on words starting with capital letter
我想使用UTF中的几个句子,并根据第一个大写字母进行拆分。
例子:
"Tough Fox" -> "Tough", "Fox"
"Nice White Cat" -> "Nice", "White Cat"
"This is a lazy Dog" -> "This is a lazy", "Dog"
"This is hardworking Little Ant" -> "This is hardworking", "Little Ant"
pythonic进行这种拆分的方法是什么?
我会用re:
>>> import re
>>> l = ["Tough Fox", "Nice White Cat", "This is a lazy Dog" ]
>>> for i in l:
... print re.findall("[A-Z][^A-Z]*", i)
...
['Tough ', 'Fox']
['Nice ', 'White ', 'Cat']
['This is a lazy ', 'Dog']
编辑:好的,我认为那是一个错误。 所以现在我来晚了, re.split(..., s, maxsplit=1)
是恕我直言的最佳方法,但是如果没有maxsplit,您仍然可以这样做:
>>> for i in l:
... print re.findall("^[^ ]*|[A-Z].*", i)
...
['Tough', 'Fox']
['Nice', 'White Cat']
['This', 'Dog']
如果要在空格后的每个大写字母上拆分字符串
import re
s = "Tough Fox"
re.split(r"\s(?=[A-Z])", s, maxsplit=1)
['Tough', 'Fox']
re.split
方法等效于Python内置的str.split
,但允许将正则表达式用作拆分模式。
正则表达式首先查找空白( \\s
)作为拆分模式。 此模式将被re.split
操作吃掉。
(?=...)
部分告诉您是一个预读谓词表达式。 字符串中的下一个字符必须与此谓词匹配(在这种情况下为大写字母[AZ]
)。 但是,这部分不被视为比赛的一部分,因此re.split
操作不会将其吃掉。
maxsplit=1
将确保仅发生一次拆分(最多两项)。
可能是这样的:
In [1]: import re
In [2]: def split(s):
...: return re.split(r'\W(?=[A-Z])', s, 1)
...:
In [3]: l = ["Tough Fox", "Nice White Cat", "This is a lazy Dog" ]
In [4]: for s in l:
...: print(split(s))
...:
['Tough', 'Fox']
['Nice', 'White Cat']
['This is a lazy', 'Dog']
使用re.split()
有一个限制:
space_split = re.compile(r'\s+(?=[A-Z])')
result = space_split.split(inputstring, 1)
演示:
>>> import re
>>> space_split = re.compile(r'\s+(?=[A-Z])')
>>> l = ["Tough Fox", "Nice White Cat", "This is a lazy Dog" ]
>>> for i in l:
... print space_split.split(i, 1)
...
['Tough', 'Fox']
['Nice', 'White Cat']
['This is a lazy', 'Dog']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.