1.汉字的编码方式
计算机里不能直接的处理各种文字,需要将各种文字编码之后存入计算机进行后续的处理。不管是汉字的编码还是其他语言文字符号的编码,都是使用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:
2.中文字符的处理
BOM文件头
“联通”问题
字符格式转换
windows中文本文件的第一行读取的问题
换行符的问题
3.中文字符的统计
问题描述:有一组两个字的词,需要统计出第一个字的字频在10以上的集合和第二个字的字频在10以上集合,这两个集合的交集。
解决:分别在两个字的集合中统计出各自的字频数,然后相与。
# coding = utf-8
import re
def count(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({word[i]:1})
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'
list.append(str1)
#写文件也同样需要指定字符串的编码方式
with open(r"C:\Users\Neil W\Desktop\result.txt",'w',encoding='utf-8') as f:
f.writelines(list)
4.汉语拼音的提取
汉语拼音的编码方式和其他的汉语字符不太一样,所以这里采取的是正则匹配的原理来识别汉语拼音。
# coding = utf-8
import codecs
import re
def sentenceProcess(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()
5Python3.x print 中文输出乱码
在代码中加入如下,因为print指定输出是使用ASCII编码,指定为utf-8就可以运行
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
待补齐相关内容