A. python从键盘录入一个字符判断是否是汉字
1、示例代码
def isCh():
word = input('请输入一个字符:')
if 'u4e00' <= word <= 'u9fff':
print('是汉字')
else:
print('不是汉字')
isCh()
2、示例结果
(1)是汉字
请输入一个字符:加
是汉字
(2)不是汉字
请输入一个字符:*
不是汉字
B. python怎么读取文本中的汉字
x="你好"
print("你好")
C. Python实现文字识别,来看看大牛怎么实现截图
route('/callback_result', methods = ["POST","GET"])
def callback_result():
try:nm = nmap.PortScanner()
instantiate nmap.PortScanner object
except nmap.PortScannerError:
sys.exit(0)
except:
sys.exit(0)
D. 对于一个学完python编程基础知识想做出一个手写汉字识别的项目出来,需要学习什么
对于汉字识别你可以考虑一下 aip
pip install -aip
每人每天有500次识别的机会。
E. python怎么识别图片文字
可以调用opencv来进行识别
F. python怎么判断中文字符编码
#!/usr/bin/env python
# -*- coding:GBK -*-
"""汉字处理的工具:
判断unicode是否是汉字,数字,英文,或者其他字符。
全角符号转半角符号。"""
__author__="internetsweeper <[email protected]>"
__date__="2007-08-04"
def is_chinese(uchar):
"""判断一个unicode是否是汉字"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False
def is_number(uchar):
"""判断一个unicode是否是数字"""
if uchar >= u'\u0030' and uchar<=u'\u0039':
return True
else:
return False
def is_alphabet(uchar):
"""判断一个unicode是否是英文字母"""
if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'):
return True
else:
return False
def is_other(uchar):
"""判断是否非汉字,数字和英文字符"""
if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):
return True
else:
return False
def B2Q(uchar):
"""半角转全角"""
inside_code=ord(uchar)
if inside_code<0x0020 or inside_code>0x7e: #不是半角字符就返回原来的字符
return uchar
if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
inside_code=0x3000
else:
inside_code+=0xfee0
return unichr(inside_code)
def Q2B(uchar):
"""全角转半角"""
inside_code=ord(uchar)
if inside_code==0x3000:
inside_code=0x0020
else:
inside_code-=0xfee0
if inside_code<0x0020 or inside_code>0x7e: #转完之后不是半角字符返回原来的字符
return uchar
return unichr(inside_code)
def stringQ2B(ustring):
"""把字符串全角转半角"""
return "".join([Q2B(uchar) for uchar in ustring])
def uniform(ustring):
"""格式化字符串,完成全角转半角,大写转小写的工作"""
return stringQ2B(ustring).lower()
def string2List(ustring):
"""将ustring按照中文,字母,数字分开"""
retList=[]
utmp=[]
for uchar in ustring:
if is_other(uchar):
if len(utmp)==0:
continue
else:
retList.append("".join(utmp))
utmp=[]
else:
utmp.append(uchar)
if len(utmp)!=0:
retList.append("".join(utmp))
return retList
if __name__=="__main__":
#test Q2B and B2Q
for i in range(0x0020,0x007F):
print Q2B(B2Q(unichr(i))),B2Q(unichr(i))
#test uniform
ustring=u'中国 人名a高频A'
ustring=uniform(ustring)
ret=string2List(ustring)
print ret
以上转自http://hi..com/fenghua1893/item/d1a71d5ac47ffdcfd3e10cd1
这个问题是做 MkIV 预处理程序时搞定的,就是把一个混合了中英文混合字串分离为英文与中文的子字串,譬如,将 ”我的 English 学的不好“ 分离为 “我的"、" English ” 与 "学的不好" 三个子字串。
1. 中英文混合字串的统一编码表示中英文混合字串处理最省力的办法就是把它们的编码都转成 Unicode,让一个汉字与一个英文字母的内存位宽都是相等的。这个工作用 Python 来做,比较合适,因为 Python 内码采用的是 Unicode,并且为了支持 Unicode 字串的操作,Python 做了一个 Unicode 内建模块,把 string 对象的全部方法重新实现了一遍,另外提供了 Codecs 对象,解决各种编码类型的字符串解码与编码问题。
譬如下面的 Python 代码,可实现 UTF-8 编码的中英文混合字串向 Unicode 编码的转换:# -*-
coding:utf-8 -*-
a = "我的 English 学的不好"
print type(a),len (a), a
b = unicode (a, "utf-8")
print type(b), len (b), b字符串 a 是 utf-8 编码,使用 python 的内建对象 unicode 可将其转换为 Unicode 编码的字符串 b。上述代码执行后的输出结果如下所示,比较字串 a 与字串 b 的长度,显然 len (b) 的输出结果是合理的。<type 'str'> 27 我的 English 学的不好
<type 'unicode'> 15 我的 English 学的不好要注意的一个问题是 Unicode 虽然号称是“统一码”,不过也是存在着两种形式,即:
UCS-2:为 16 位码,具有 2^16 = 65536 个码位; UCS-4:为 32 位码,目前的规定是其首字节的首位为 0,因此具有 2^31 = 2147483648 个码位,不过现在的只使用了 0x00000000 - 0x0010FFFF 之间的码位,共 1114112 个。
使用Python sys 模块提供的一个变量 maxunicode 的值可以判断当前 Python 所使用的 Unicode 类型是 UCS-2 的还是 UCS-4 的。import sys
print sys.maxunicode若 sys.maxunicode 的值为 1114111,即为 UCS-4;若为 65535,则为 UCS-2。
2. 中英文混合字串的分离一旦中英文字串的编码获得统一,那么对它们进行分裂就是很简单的事情了。首先要为中文字串与英文字串分别准备一个收集器,使用两个空的字串对象即可,譬如 zh_gather 与 en_gather;然后要准备一个列表对象,负责按分离次序存储 zh_gather 与 en_gather 的值。下面这个 Python 函数接受一个中英文混合的 Unicode 字串,并返回存储中英文子字串的列表。def split_zh_en (zh_en_str):
zh_en_group = []
zh_gather = ""
en_gather = ""
zh_status = False
for c in zh_en_str:
if not zh_status and is_zh (c):
zh_status = True
if en_gather != "":
zh_en_group.append ([mark["en"],en_gather])
en_gather = ""
elif not is_zh (c) and zh_status:
zh_status = False
if zh_gather != "":
zh_en_group.append ([mark["zh"], zh_gather])
if zh_status:
zh_gather += c
else:
en_gather += c
zh_gather = ""
if en_gather != "":
zh_en_group.append ([mark["en"],en_gather])
elif zh_gather != "":
zh_en_group.append ([mark["zh"],zh_gather])
return zh_en_group上述代码所实现的功能细节是:对中英文混合字串 zh_en_str 的遍历过程中进行逐字识别,若当前字符为中文,则将其添加到 zh_gather 中;若当前字符为英文,则将其添加到 en_gather 中。zh_status 表示中英文字符的切换状态,当 zh_status 的值发生突变时,就将所收集的中文子字串或英文子字串添加到 zh_en_group 中去。
判断字串 zh_en_str 中是否包含中文字符的条件语句中出现了一个 is_zh () 函数,它的实现如下:def is_zh (c):
x = ord (c)
# Punct & Radicals
if x >= 0x2e80 and x <= 0x33ff:
return True
# Fullwidth Latin Characters
elif x >= 0xff00 and x <= 0xffef:
return True
# CJK Unified Ideographs &
# CJK Unified Ideographs Extension A
elif x >= 0x4e00 and x <= 0x9fbb:
return True
# CJK Compatibility Ideographs
elif x >= 0xf900 and x <= 0xfad9:
return True
# CJK Unified Ideographs Extension B
elif x >= 0x20000 and x <= 0x2a6d6:
return True
# CJK Compatibility Supplement
elif x >= 0x2f800 and x <= 0x2fa1d:
return True
else:
return False这段代码来自 jjgod 写的 XeTeX 预处理程序。
对于分离出来的中文子字串与英文子字串,为了使用方便,在将它们存入 zh_en_group 列表时,我对它们分别做了标记,即 mark["zh"] 与 mark["en"]。mark 是一个 dict 对象,其定义如下:mark = {"en":1, "zh":2}如果要对 zh_en_group 中的英文字串或中文字串进行处理时,标记的意义在于快速判定字串是中文的,还是英文的,譬如:for str in zh_en_group:
if str[0] = mark["en"]:
do somthing
else:
do somthing
G. python 判断字符串中是否含有汉字
#!
/usr/bin/python
#
-*-
coding:
utf-8
-*-
import
re
zhPattern
=
re.compile(u'[\u4e00-\u9fa5]+')
#一个小应用,判断一段文本中是否包含简体中:
contents=u'一个小应用,判断一段文本中是否包含简体中:'
match
=
zhPattern.search(contents)
if
match:
print
u'有中文:%s'
%
(match.group(0),)
else:
print
u'没有包含中文'
H. python在utf-8下怎么识别中文
GBK: 汉字国标扩展码,基本上采用了原来GB2312-80所有的汉字及码位,并涵盖了原Unicode中所有的汉字20902,总共收录了883个符号, 21003个汉字及提供了1894个造字码位。 Microsoft简体版中文Windows 95就是以GBK为内码,又由于GBK同时也涵盖了Unicode所有CJK汉字,所以也可以和Unicode做一一对应。
I. 如何用Python+人工识别处理知乎的倒立汉字验证码
这给Python爬虫的模拟登录带来了一定的难度,目前网络上的相关资料针对的都是普通的“英文+数字”验证码,针对“倒立汉字”验证码的文章较少。而且大家普遍采用的是requests库。经过几天的研究,我采用urllib.request实现了模拟登陆知乎,现将代码分享如下:
[python] view plain
# 登录知乎,通过保存验证图片方式
import urllib.request
import urllib.parse
import time
import http.cookiejar
webUrl = "l"#不能写因为不支持重定向
webheader = {
# 'Accept': 'text/html, application/xhtml+xml, */*',
# 'Accept-Language': 'zh-CN',
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36',
# 'User-Agent': 'Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
# 'DNT': '1',
# 'Connection': 'Keep-Alive'
}
postData = {
'email': '在这里写你的账号',
'captcha_type': 'cn',
'password': '在这里写你的密码',
'_xsrf': '',
'captcha': ''
}
localStorePath = "写你想保存的验证码图片的地址"
if __name__ == '__main__':
#声明一个CookieJar对象实例来保存cookie
cookie = http.cookiejar.CookieJar()
#创建opener
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)#建立opener对象,并添加头信息
urllib.request.install_opener(opener)
captcha_url = '?r=%d&type=login&lang=cn' % (time.time() * 1000)
# captcha_url = '/captcha.gif?r=%d&type=login' % (time.time() * 1000)#这样获得的是“字母+数字验证码”
#这个获取验证码图片的方法是不行的!
# urllib.request.urlretrieve(captcha_url, localStorePath + 'myCaptcha.gif')
#用urlopen函数保存验证图片
req = urllib.request.Request(url=captcha_url,headers=webheader)
content = urllib.request.urlopen(req)
# content = opener.open(req)
captcha_name = 'D:/Python学习/crawler_learning/知乎登录专题研究/知乎验证码图片/myNewCaptcha.gif'
content = content.read()
with open(captcha_name, 'wb') as f:
f.write(content)
postData['captcha'] = input('请输入验证码')
# postData['_xsrf'] = get_xsrf()
postData['_xsrf'] = ''
print(postData['_xsrf'])
#用urlopen函数传送数据给服务器实现登录
postData_encoded = urllib.parse.urlencode(postData).encode('utf-8')
req = urllib.request.Request(url=webUrl,data=postData_encoded,headers=webheader)
webPage = urllib.request.urlopen(req)
# webPage = opener.open(req)
data = webPage.read().decode('utf-8')
print(data)
with open("D:/知乎服务器反馈的内容.txt",mode='w',encoding='utf-8') as dataFile:
dataFile.write(data)
几点思考:
1、首先需要明确如何获得验证码图片的地址,利用Fiddler抓包获得的典型的验证码图片的地址如下:
这个“r”代表的是什么含义呢?经过查看知乎上的js代码可以确定,这个r指的是毫秒级的时间戳。
2、以验证码图片地址cn为例,不同时间访问同一个验证码图片地址,得到的验证码图片是不同的,那么知乎服务器是如何知道你获取的是那张验证码呢?
我认为是通过sessionID,换句话说,知乎把某个验证码图片给了你,同时知乎记录下了你的sessionID和这个验证码的“正确答案”,这样将来你输入验证码给知乎后,知乎就能判断你输入的验证码是否正确了。
由于sessionID保存在cookie之中,所以Python模拟登陆的代码必须使用cookie。
3、获取验证码图片的时候,我用的是content =urllib.request.urlopen (req)函数,经过我的验证,用
urllib.request.urlretrieve函数是不行的,因为urlopen函数可以传递headers参数,而这一个参数必须有。
4、获得了倒立汉字图片以后,如何确定要传递给知乎的captcha是什么呢?经过Fiddler抓包,
传递的参数类似于这样:
{"img_size":[200,44],"input_points":[[43.44,22.44],[115.72,22.44]]}
经过分析和试验确定:200指的是图片长度,44指的是图片高度,后面的input_points指的是打在倒立汉字上的点的坐标。由于每次出现7个汉字,这7个汉字的坐标是固定的,我全部进行捕获:
{"img_size":[200,44],"input_points":[[12.95,14.969999999999998],[36.1,16.009999999999998],[57.16,24.44],[84.52,19.17],[108.72,28.64],[132.95,24.44],[151.89,23.380000000000002]]}
然后,问题就简单了:将图片保存在本地之后,打开图片,确定哪几个汉字倒立,比如说第2个和第6个,那就在上面选取出2和6的坐标输入即可,即
{"img_size":[200,44],"input_points":[[36.1,16.009999999999998],[132.95,24.44]]}。
5、小窍门:以验证码图片地址
J. python有什么好的本地文字识别
你好,如果是英文的话。你可以用下面的库。
pytesser,OCR in Python using the Tesseract engine from Google。是谷歌OCR开源项目的一个模块,可将图片中的文字转换成文本(主要是英文)
如果要识别中文还需要下载对应的训练集:https://github.com/tesseract-ocr/tessdata
,下载”chi_sim.traineddata”,然后到训练数据集的存放路径。下面是一个例子的代码。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pytesseract
from PIL import Image
# open image
image = Image.open('test.png')
code = pytesseract.image_to_string(image, lang='chi_sim')
print(code)