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)