首页 > 解决方案 > 正则表达式在 python 中的 unicode 单词/数字之间添加空格

问题描述

我尝试对 unicode 使用基本的正则表达式,但我无法使它们在具有传统 AZ 和数字以外的字符的字符串上工作

我正在查看不属于 AZ Alphabetical 家族的多种语言的示例

text = "20किटल"
res = re.sub("^[^\W\d_]+$", lambda ele: " " + ele[0] + " ", text)

Output:
20किटल

第二次尝试:

regexp1 = re.compile('^[^\W\d_]+$', re.IGNORECASE | re.UNICODE)
regexp1.sub("^[^\W\d_]+$", lambda ele: " " + ele[0] + " ", text)

 Output:
 20किटल


Expected output:
**20 किटल**

标签: pythonregexunicodenlpindic

解决方案


使用Pypi 正则表达式库

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import regex

text = "20किटल"
pat = regex.compile(r"(?<=\d)(?=\p{L})", re.UNICODE)
res = pat.sub(" ", text)
print res

代表\p{L}任何语言的任何字母

输出:

20 किटल

推荐阅读