Python 2.7:测试字符串中的字符是否全是中文字符。

8
以下代码测试字符串中的字符是否都是汉字,它适用于Python 3,但不适用于Python 2.7。在Python 2.7中如何实现这个功能?
for ch in name:
    if ord(ch) < 0x4e00 or ord(ch) > 0x9fff:
        return False

4
“name”是Unicode字符串还是字节字符串?顺便说一下,你不需要在这里使用“ord”:其中if ch < u'\u4e00' or ch > u'\u9fff':也可以起作用。 - Martijn Pieters
1
相关内容:https://dev59.com/V3DYa4cB1Zd3GeqPGPv9#16028174 - Daenyth
2个回答

12
#  byte str (you probably get from GAE)
In [1]: s = """Chinese (汉语/漢語 Hànyǔ or 中文 Zhōngwén) is a group of related
        language varieties, several of which are not mutually intelligible,"""

#  unicode str
In [2]: us = u"""Chinese (汉语/漢語 Hànyǔ or 中文 Zhōngwén) is a group of related
        language varieties, several of which are not mutually intelligible,"""

#  convert to unicode using str.decode('utf-8')    
In [3]: print ''.join(c for c in s.decode('utf-8') 
                   if u'\u4e00' <= c <= u'\u9fff')
汉语漢語中文

In [4]: print ''.join(c for c in us if u'\u4e00' <= c <= u'\u9fff')
汉语漢語中文
为确保所有字符均为中文,可以使用类似以下方式的内容:

all(u'\u4e00' <= c <= u'\u9fff' for c in name.decode('utf-8'))

在您的 Python 应用程序中,内部使用 Unicode - 尽早解码 & 晚期编码 - 创建一个Unicode 三明治


只有一个注释 - 与其将其解码为一次性值,最好将解码后的Unicode对象存储起来,并在内部使用Unicode进行操作。 - Marcin
@Marcin--你说得完全正确,我会添加一个注释,谢谢。 - root

5

对我来说,在Python 2.7中这个工作做得很好,只要name是一个unicode()

>>> ord(u'\u4e00') < 0x4e00
False
>>> ord(u'\u4dff') < 0x4e00
True

在此处,如果您直接将字符与Unicode值进行比较,则不必使用ord

>>> u'\u4e00' < u'\u4e00'
False
>>> u'\u4dff' < u'\u4e00'
True

来自请求的数据尚未解码为Unicode,您需要先进行解码。明确设置表格标签上的accept-charset属性,以确保浏览器使用正确的编码:

<form accept-charset="utf-8" action="...">

然后在服务器端解码数据:

name = self.request.get('name').decode('utf8')

1
我正在使用Python开发Google App Engine。通过表单获取name的值,代码为name = self.request.get('name'),用户只能输入中文字符。我需要将name转换成Unicode吗?如果需要,应该如何转换? - Randy Tang
1
@唐:是的,你需要先将数据转换为Unicode。浏览器通常使用HTML页面的编码,因此如果您使用Content-Type: text/html; charset=utf8提供页面,则可以假定您也可以解码为UTF-8。 - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接