Pau*_*jan 10 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
Run Code Online (Sandbox Code Playgroud)
所以这对于英语非常有用,而英语就像字符串一样,但对于中文字符串来说却失败了,因为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']
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能处理I18N?这在所有语言中都有意义吗?
如果重要的话,我正在使用python 2.5.4.
中文通常在单词之间没有空格,符号可以根据上下文有不同的含义.您必须了解文本才能将其拆分为单词边界.换句话说,一般来说,你要做的事情并不容易.
在与一些以粤语、普通话和日语为母语的人交谈后,似乎正确的做法很难,但我当前的算法在互联网帖子的背景下对他们来说仍然有意义。
\n\n意思是,它们习惯于“分割空间并在末尾添加 \xe2\x80\xa6”处理。
\n\n所以我会偷懒并坚持下去,直到我收到不理解它的人的抱怨为止。
\n\n对我原始实现的唯一更改是不要在最后一个单词上强制使用空格,因为在任何语言中都不需要空格(并使用 unicode 字符 \xe2\x80\xa6…
而不是 ...three dots
来保存 2 个字符)
归档时间: |
|
查看次数: |
6617 次 |
最近记录: |