问题描述
欧珑 无极乌龙 Atelier Cologne Oolang Infini,2010
如何将其拆分为两个字符串的数组? ['欧珑 无极乌龙','Atelier Cologne Oolang Infini,2010']
我尝试过:
names = re.split(r'([a-zA-Z]+)',names)
但是它给出了:
names: ['欧珑 无极乌龙 ','Atelier',' ','Cologne','Oolang','Infini',',2010']
解决方法
一种快速简单的正则表达式,用于区分 latin 和 non-latin 部分(regex101 demo)。
(?i)[^a-z\d]+|[_a-z\d\W]+
与re.findall
(tio.run demo)一起使用。正则表达式很容易自我解释和匹配
- one or more个拉丁字母或数字的
[^a-z\d]+
not个字符 - 或
[_a-z\d\W]+
一个或多个,即_
拉丁字母,数字或非word-characters
速度很快,但是您需要从结果中修剪空白。否则会变得更加复杂:)要在结果中区分 拉丁 / 非拉丁,您可以将finditer
与{{ 3}}(groups)。
import re
text = '欧珑 无极乌龙 Atelier Cologne Oolang Infini,2010 乌龙乌 foo$'
pattern = '(?i)([^a-z\d]+)|([_a-z\d\W]+)'
for m in re.finditer(pattern,text):
if(m.group(1)):
print("non-latin:\t'" + m.group(1).strip() + "'")
if(m.group(2)):
print("latin:\t\t'" + m.group(2).strip() + "'")