gpt4 book ai didi

python 2.7 : test if characters in a string are all Chinese characters

转载 作者:太空狗 更新时间:2023-10-29 20:40:55 24 4
gpt4 key购买 nike

下面的代码测试字符串中的字符是否都是汉字。它适用于 Python 3 但不适用于 Python 2.7。我如何在 Python 2.7 中执行此操作?

for ch in name:
if ord(ch) < 0x4e00 or ord(ch) > 0x9fff:
return False

最佳答案

#  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 sandwich .

关于 python 2.7 : test if characters in a string are all Chinese characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16441633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com