Python:在单词边界上拆分 unicode 字符串

标签 python unicode internationalization character-properties

我需要取一个字符串,并将其缩短为 140 个字符。

目前我在做:

if len(tweet) > 140:
    tweet = re.sub(r"\s+", " ", tweet) #normalize space
    footer = "… " + utils.shorten_urls(post['url'])
    avail = 140 - len(footer)
    words = tweet.split()
    result = ""
    for word in words:
        word += " "
        if len(word) > avail:
            break
        result += word
        avail -= len(word)
    tweet = (result + footer).strip()
    assert len(tweet) <= 140

所以这对于英语和类似字符串的英语非常有用,但对于中文字符串却失败了,因为 tweet.split() 只返回一个数组:

>>> s = u"简讯:新華社報道,美國總統奧巴馬乘坐的「空軍一號」專機晚上10時42分進入上海空域,預計約30分鐘後抵達浦東國際機場,開展他上任後首次訪華之旅。"
>>> s
u'\u7b80\u8baf\uff1a\u65b0\u83ef\u793e\u5831\u9053\uff0c\u7f8e\u570b\u7e3d\u7d71\u5967\u5df4\u99ac\u4e58\u5750\u7684\u300c\u7a7a\u8ecd\u4e00\u865f\u300d\u5c08\u6a5f\u665a\u4e0a10\u664242\u5206\u9032\u5165\u4e0a\u6d77\u7a7a\u57df\uff0c\u9810\u8a08\u7d0430\u5206\u9418\u5f8c\u62b5\u9054\u6d66\u6771\u570b\u969b\u6a5f\u5834\uff0c\u958b\u5c55\u4ed6\u4e0a\u4efb\u5f8c\u9996\u6b21\u8a2a\u83ef\u4e4b\u65c5\u3002'
>>> s.split()
[u'\u7b80\u8baf\uff1a\u65b0\u83ef\u793e\u5831\u9053\uff0c\u7f8e\u570b\u7e3d\u7d71\u5967\u5df4\u99ac\u4e58\u5750\u7684\u300c\u7a7a\u8ecd\u4e00\u865f\u300d\u5c08\u6a5f\u665a\u4e0a10\u664242\u5206\u9032\u5165\u4e0a\u6d77\u7a7a\u57df\uff0c\u9810\u8a08\u7d0430\u5206\u9418\u5f8c\u62b5\u9054\u6d66\u6771\u570b\u969b\u6a5f\u5834\uff0c\u958b\u5c55\u4ed6\u4e0a\u4efb\u5f8c\u9996\u6b21\u8a2a\u83ef\u4e4b\u65c5\u3002']

我应该怎么做才能处理 I18N?这对所有语言都有意义吗?

如果重要的话,我正在使用 python 2.5.4。

最佳答案

中文单词之间通常没有空格,符号可以根据上下文有不同的含义。您必须理解文本才能在单词边界处拆分它。换句话说,您要尝试做的事情通常并不容易。

关于Python:在单词边界上拆分 unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1738788/

相关文章:

java String.Format ("%02d")产生奇怪的 unicode 字符

php - 将 Unicode 字符转换为等效的 ASCII 字符

PHP:子域上的多语言网站,没有许多 public_html 副本

javascript - 在一个 javascript 文件中为整个网站创建标签

Matlab A( :, 1)' 和 A(:) 的 Python 等效项

python - 使用 lxml 从 xml 中提取嵌套命名空间

string - Lua unicode,使用 string.sub() 和两字节字符

python - 计算特定值的两个二维二进制 numpy 数组的重叠值

python - 如何用非分类数据绘制 "grouped scatterplot"?

c++ - QApplication 的 installTranslator 方法不改变语言