2007-06-15

 

Python Cook 1.11 判断字符串中是文本还是字节流

需求:

Python可以使用string来保存字符串或任意字节.我们需要判断字符串中的是文本,还是字节流,目前还没有什么明确的算法来区分两种情况.

讨论:

我们需要自己设计出算法来区分字节流和字符串,比如判断是否有超过30%的字节都包含着空字符,控制字符或者非ascii字符(字节高位设置为1),我们必须要自己处理,也要为不同的场景设计出不同的算法:

from _ _future_ _ import division # ensure / does NOT truncate
import string
text_characters = "".join(map(chr, range(32, 127))) + "\n\r\t\b"
_null_trans = string.maketrans("", "")
def istext(s, text_characters=text_characters, threshold=0.30):
    # if s contains any null, it's not text:
    if "\0" in s:
        return False
    # an "empty" string is "text" (arbitrary but reasonable choice):
    if not s:
        return True
    # Get the substring of s made up of non-text characters
    t = s.translate(_null_trans, text_characters)
    # s is 'text' if less than 30% of its characters are non-text ones:
    return len(t)/len(s) <= threshold

可以通过设置istext的threshold参数来定制算法,也可以通过修改text_characters参数来改变字符集.比如,如果需要判断ISO-8859-1编码的意大利重音字符,就需要添加重音符号给text_characters,如" àèéìÃ2Ã1"

上面的代码中需要注意的是,/做整数除法,不会截断小数点,如果要取整除法,请使用//. 默认情况下,如果除数和被除数都是整数,那么结果也是整数.

例如:

>>>5 / 3
1
>>>5 // 3
1
>>>5.0 / 3
1.6666666666666667
>>>5.0 // 3
1.0

所以在例子的第一行我们写了:

from _ _future_ _ import division

这保证在我们的代码中,被除数和除数都是整数时,它们的结果依然可以是小数.

相关说明:

from __future__ import division 请放在代码的 第一句,我自己安装SOAPpy库时,就因为这个问题不能正常安装,修改代码后安装成功了.

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?