python漢字的處理

2021-08-09 11:25:28 字數 2763 閱讀 8617

計算機裡不能直接的處理各種文字,需要將各種文字編碼之後存入計算機進行後續的處理。不管是漢字的編碼還是其他語言文字元號的編碼,都是使用01的不同組合序列來表示不同的符號。

ascii編碼:american standard code for information interchange,美國資訊互換標準**。ascii編碼使用乙個8位的二進位制(1byte=8bit)組成,總的數量有256個。其中常用的a-z、a-z、數字0-9、控制字元(空格、換行等等)等等。

gb2312:

gb2300:

unicode:

utf-8:

utf-16:

bom檔案頭

「聯通」問題

字元格式轉換

windows中文字檔案的第一行讀取的問題

換行符的問題

問題描述:有一組兩個字的詞,需要統計出第乙個字的字頻在10以上的集合和第二個字的字頻在10以上集合,這兩個集合的交集。

解決:分別在兩個字的集合中統計出各自的字頻數,然後相與。

# coding = utf-8

import re

defcount

(dict,i):

#定義字典,來儲存字和字的個數

word1 = {}

label = 0;

#統計字出現的次數,返回字典

for word in dict:

#跳過檔案中的第一行,第一行的字元編碼有些奇怪,直接跳過處理第二行

if label == 0:

label = 1

continue

if word[i] in word1:

word1[word[i]] += 1

else:

word1.update()

return word1

if __name__ == "__main__":

#開啟檔案,注意必須指明用檔案使用的編碼方式,這是需要告知python編輯器使用相同的解碼器進行解碼,python預設的中文解碼器是gbk解碼器

with open(r"c:\users\neil w\desktop\source1.txt",'r',encoding='utf-8') as f:

dict = f.readlines()

word1 = count(dict,0)

word2 = count(dict,1)

list =

label = 0

#在字典中查詢字出現的次數

for word in dict:

if label == 0:

label = 1

continue

if word1[word[0]] >= 10

and word2[word[1]] >= 10:

str1 = word[0:2] + " " + str(word1[word[0]]) + " " + str(word2[word[1]]) + '\n'

#寫檔案也同樣需要指定字串的編碼方式

with open(r"c:\users\neil w\desktop\result.txt",'w',encoding='utf-8') as f:

f.writelines(list)

漢語拼音的編碼方式和其他的漢語字元不太一樣,所以這裡採取的是正則匹配的原理來識別漢語拼音。

# coding = utf-8

import codecs

import re

defsentenceprocess

(s):

regex = re.compile(r'[a-z]*[āāáǎàōóǒòêēéěèīíǐìūúǔùǖǘǚǜüńňǹɑɡ]+[\』|a-z|a-z]*[āāáǎàōóǒòêēéěèīíǐìūúǔùǖǘǚǜüńňǹɑɡ|a-z|a-z]*')

if s == '\n':

print(s.encode())

return -1

pinyin = regex.findall(s)

if len(pinyin) == 0:

return s

remain = regex.split(s)

pinyin[0] = "$" + pinyin[0] + "$"

each = u""

i = 0

for x in remain:

if i < len(pinyin):

each = each + x + pinyin[i]

i += 1

else:

each = each + x

return each

if __name__ == '__main__':

file1 = open(r"c:\users\neil w\desktop\result.txt",'w',encoding='utf-8')

with open(r"c:\users\neil w\desktop\1.txt",encoding='utf-8') as f:

z = f.readlines()

for x in z:

sentence = sentenceprocess(x)

if sentence != -1:

file1.writelines(sentence)

file1.close()

在**中加入如下,因為print指定輸出是使用ascii編碼,指定為utf-8就可以執行

import io

import sys

python處理漢字的拼音

一 漢字拼音轉換工具 python 版 二 安裝 pip install pinyin三 例項 import pinyin as py print py.get 我是乙個中國人 print py.get initial 我是乙個中國人 print type py.get initial 我是乙個中國...

python處理漢字轉拼音pypinyin

主要是pypinyin 包,官網 jieba包,主要是用來分詞的,我之前的博文有介紹 官網 就不細講了,軟體包都是中國人寫的,官網也都是中文,看上去無壓力。放一下我的練習例項 usr bin env python coding utf 8 time 17 12 12 下午4 09 author da...

JAVA處理漢字

1.在url附帶中文引數,可以直接讀取。例如 request.getparameter showword 2 與資料庫有關的各種sql操作 這裡使用的access沒有發生問題。jdbc中文處理 一,取中文 處理 將資料按 iso 8859 1 格式轉為位元組陣列,再按系統預設編碼格式 default...