2025年3月29日 星期六 甲辰(龙)年 月廿八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python判断字符串是中文还是英文

时间:08-22来源:作者:点击数:21
  • 判断字符串为全中文
  • #检验是否全是中文字符
  • def is_all_chinese(strs):
  • for _char in strs:
  • if not '\u4e00' <= _char <= '\u9fa5':
  • return False
  • return True
  • >>> a = "你好";b = "</p>你好"
  • #或者用 all()
  • >>> all(map(lambda c:'\u4e00' <= c <= '\u9fa5',a))
  • True
  • >>> all(map(lambda c:'\u4e00' <= c <= '\u9fa5',b))
  • False

详细的unicode分区信息可以参考这里:中日韩统一表意文字

中文在unicode里的分区码段:

1、中日韩扩展部首[2E80-2EFF](116字)

2、康熙字典部首[2F00-2FDF](214字)

3、表意文字描述字符[2FF0-2FFF](12字)

4、中日韩笔画[31C0-31EF](37字)

5、中日韩统一表意文字扩展A区[3400-4DBF](6582字)

6、中日韩统一表意文字[4E00-9FFF](20940字)

7、私用区[E000-F8FF](896字)

8、中日韩兼容表意文字[F900-FAFF](471字)

9、中日韩统一表意文字扩展B区[20000-2A6DF](42711字)

10、中日韩统一表意文字扩展C区[2A700-2B73F](4149字)

11、中日韩统一表意文字扩展D区[2B740-2B81F](222字)

12、中日韩统一表意文字增补集[2F800-2FA1F](542字)

13、增补私用A区[F0000-FFFFF](73字)

  • 判断字符串是否包含中文
  • #检验是否含有中文字符
  • def is_contains_chinese(strs):
  • for _char in strs:
  • if '\u4e00' <= _char <= '\u9fa5':
  • return True
  • return False
  • 正则判断中文
  • import re
  • key='123中文'
  • zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
  • match = zhPattern.search(key)
  • if match:
  • print("存在中文")
  • 正则判断是否含有英文和数字

判断有数字:

  • re.match(r'[+-]?\d+$', s) s 为数字, 返回数字位置 ,
  • not re.match(r'[+-]?\d+$', s) 返回为True说明不含有数字

判断有英文字符:

  • re.match(r'[a-z]+',s) 返回小写字母位置
  • re.match(r'[a-z]+',s,re.I) 对大小写敏感。返回字母位置
  • not re.match(r'[a-z]+',s,re.I) 返回为True说明没有英文字符
  • regex
  • >>> import regex
  • >>> zh = regex.compile(r'^\p{Han}*$')
  • >>> zh.match('你好')
  • <regex.Match object; span=(0, 2), match='你好'>
  • >>> zh.match('<p>好')
  • >>>

只能保证是汉字,不能保证是中文,也可能是日文。

  • 逐个字符用ord()判断ascii码

a - z : 97 - 122

A - Z : 65 - 90

  • def is_english_char(ch):
  • if ord(ch) not in (97,122) and ord(ch) not in (65,90):
  • return False
  • return True
  • 判断英文
  • #判断英文
  • st = "我爱中国I love China"
  • for s in st:
  • if (u'\u0041'<= s <= u'\u005a') or (u'\u0061'<= s <= u'\u007a'):
  • print("%s 是英文" %s)
  • 判断数字
  • #判断数字
  • st = "我爱中国I love China 520"
  • for s in st:
  • if s.isdigit():
  • print("%s 是数字" %s)
  • 判断空格
  • #判断空格
  • st = "我爱中国I love China 520"
  • for s in st:
  • if s.isspace():
  • print("%s 是空格" %s)
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐