【问题标题】:python to remove space between Chinese unicode strings but not between English wordspython删除中文unicode字符串之间的空格,但不删除英文单词之间的空格
【发布时间】:2017-08-24 11:47:15
【问题描述】:

需要python正则表达式的帮助,我有一个包含中文和英文的字符串,我想删除汉字之间的空格,而不是英文单词之间的空格。

来自 -- "u'\u5c0f \u5973 \u4eca \u5e74 \u4fc2 dse \u8003 \u751f \u5979 \u559c \u6b61 filmtv \u524d \u5e7e \u65e5 in \u5de6 buasso-filmtv 和数字媒体研究 \u5df2 \ u7d93 condition offer \u4f46 \u60f3 \u554f \u5982 \u679c through jupas openu \u6536 \u5979 \u8b80 创意写作和电影艺术荣誉文学士”

to -- "u'\u5c0f\u5973\u4eca\u5e74\u4fc2 dse \u8003\u751f\u5979\u559c\u6b61 filmtv \u524d\u5e7e\u65e5 in \u5de6 buasso-filmtv 和数字媒体研究 \u5df2\ u7d93 condition offer \u4f46\u60f3\u554f\u5982\u679c through jupas openu \u6536\u5979\u8b80 创意写作和电影艺术荣誉文学士”

仅在两个 unicode 字符之间删除空格

【问题讨论】:

  • 似乎没有很好的内置函数来发现 Unicode 块,或者 python re 中对 Unicode 的良好支持。我想您应该使用regex 包来更具体地处理 Unicode(在这种情况下,您可能想要使用 Unicode 脚本或 Unicode 块)。否则,您将不得不在正则表达式中手动列出 Unicode 块。
  • 是的,python re函数不区分中文和英文,都是unicode,不能只搜索unicode字符。

标签: python regex string unicode


【解决方案1】:

如果您可以将“unicode 字符”定义为“非 ASCII”字符,那么您可以使用 negative lookahead/lookbehind

re.sub("(?<![ -~]) (?![ -~])", "", text)

如果您不喜欢使用的范围 ([ -~]),那么 this question has some alternatives。此外,还有多种unicode categories 可能更好地满足您的目的,但据我所知,您仍然需要手动定义字符范围,因为它们在 re 模块中不受支持。

【讨论】: