新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python中文生僻字的識(shí)別
問題點(diǎn)

本來考慮用正則來判斷中文,因?yàn)榫W(wǎng)上發(fā)現(xiàn)正則的匹配中文是[\u4e00-\u9fa5]。接著代碼都快寫完了,發(fā)現(xiàn)有些生僻字不再在這個(gè)范圍內(nèi)。
識(shí)別方法
在utf-8字符編碼下,一個(gè)中文字符占3個(gè)字節(jié),但字符的長度只有1。
1、分析中文的方法是否可以靈活為len(bytes(str,'utf-8)==3 and len(string)==1。
2、文本寫作判斷中文后,如果是漢字str.ljust(5),否則為str.ljust(6)。
因?yàn)橐粋€(gè)漢字占兩個(gè)字符的長度。
實(shí)例
from pypinyin import pinyin
import re
class ChangePinyin:
def __init__(self, filename):
self.file = filename
self.lyric = self.read_file()
self.pinyin = []
def read_file(self):
with open(self.file, encoding='utf-8') as f:
return f.readlines()
def write_file(self):
with open('New_%s' % self.file, 'w', encoding='utf-8') as f:
print(self.lyric)
for line in self.lyric:
# print(line)
if line.strip() == '':
continue
_new_line = re.sub(r'\s', '', line)
# 行內(nèi)容轉(zhuǎn)拼音
_pinyin = ''.join(map(lambda x: x[0].ljust(6), pinyin(_new_line)))
# 根據(jù)中英文,將行內(nèi)容進(jìn)行字符與漢字的拆分
_lyric = self.split_words(_new_line)
f.write('%s\n%s\n' % (_pinyin, _lyric))
@staticmethod
def split_words(words):
word_list = ""
tmp = ""
for string in words:
if len(bytes(string, 'utf-8')) == 3 and len(string) == 1:
if tmp != '':
word_list += tmp.ljust(6)
tmp = ""
word_list += string.ljust(5)
else:
tmp += string
return word_list
if __name__ == '__main__':
Main = ChangePinyin('lyric.txt')
Main.write_file()以上就是python中文生僻字的識(shí)別,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
文章名稱:創(chuàng)新互聯(lián)Python教程:python中文生僻字的識(shí)別
網(wǎng)站路徑:http://fisionsoft.com.cn/article/djpdihg.html


咨詢
建站咨詢
