Python:检查字符串是否包含中文字符?

新手上路,请多包涵

一个字符串可能是这个

ipath= "./data/NCDC/上海/虹桥/9705626661750dat.txt"

或这个

ipath = './data/NCDC/ciampino/6240476818161dat.txt'

我怎么知道第一个字符串包含 chinese

我发现这个答案可能有帮助: Find all Chinese text in a string using Python and Regex

但没有成功:

 import re
ipath= "./data/NCDC/上海/虹桥/9705626661750dat.txt"
re.findall(ur'[\u4e00-\u9fff]+', ipath) # => []

原文由 cqcn1991 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 371
2 个回答

匹配的字符串也应该是 unicode

 >>> import re
>>> ipath= u"./data/NCDC/上海/虹桥/9705626661750dat.txt"
>>> re.findall(r'[\u4e00-\u9fff]+', ipath)
[u'\u4e0a\u6d77', u'\u8679\u6865']

原文由 xecgr 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您只想知道您的字符串中是否有您不需要的中文字符 re.findall ,请使用 re.search 并且匹配对象是真实的。

 >>> import re
>>> ipath= u'./data/NCDC/上海/虹桥/9705626661750dat.txt'
>>> ipath2 = u'./data/NCDC/ciampino/6240476818161dat.txt'
>>> for x in (ipath, ipath2):
...     if re.search(u'[\u4e00-\u9fff]', x):
...         print 'found chinese character in ' + x
...
found chinese character in ./data/NCDC/上海/虹桥/9705626661750dat.txt

原文由 timgeb 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题