格式化列表显示其组件的repr。如果你想自然地查看字符串而不是转义,你需要自己设置格式。 (repr应该不来逃避这些字符; repr(u'我')应该返回"u'我'",不"u'\\u6211'显然,这并在Python 3发生;只有2.X被套牢的英语为中心的转义Unicode字符串。)
基本您可以使用的算法是为每个字符分配一个字符类,然后按类分组字母。起始码在下面。
我没有使用doctest,因为我打了一些奇怪的编码问题,我不想查看(超出范围)。你需要实现一个正确的分组功能。
请注意,如果您使用此功能进行单词换行,还有其他每种语言的注意事项。例如,你不想破坏不间断的空间;你确实想打破连字符;对于日语你不想分开きゅ;等等。
# -*- coding: utf-8 -*-
import itertools, unicodedata
def group_words(s):
# This is a closure for key(), encapsulated in an array to work around
# 2.x's lack of the nonlocal keyword.
sequence = [0x10000000]
def key(part):
val = ord(part)
if part.isspace():
return 0
# This is incorrect, but serves this example; finding a more
# accurate categorization of characters is up to the user.
asian = unicodedata.category(part) == "Lo"
if asian:
# Never group asian characters, by returning a unique value for each one.
sequence[0] += 1
return sequence[0]
return 2
result = []
for key, group in itertools.groupby(s, key):
# Discard groups of whitespace.
if key == 0:
continue
str = "".join(group)
result.append(str)
return result
if __name__ == "__main__":
print group_words(u"Testing English text")
print group_words(u"我爱蟒蛇")
print group_words(u"Testing English text我爱蟒蛇")