with open(r"C:Usersmike1Desktoppractice_txt.txt","r",encoding = "gbk") as txt1, open(r"C:Usersmike1Desktop esult_txt.txt", "w", encoding = "gbk" ) as txt2: empty_dic = {} file1 = txt1.read() for i in file1: #key step :abstrack the word and count empty_dic[i] = empty_dic.get(i, 0) + 1 empty_lis = [] for i in empty_dic: empty_lis.append("{0} : {1} ".format(i, empty_dic[i] )) result = ",".join(empty_lis) txt2.write(result)
这样就把文本的没个字都提取了出来,并且把标点符号也提取了出来,但是输出的格式可能并不是很理想。
这其中有几个坑,第一个:在with open(),函数中,如果用encoding = "utf-8",会有如下错误 UnicodeDecodeError: 'utf-8' codec can't decode byte.. ,从网上查了一下,原因:utf-8编码的汉字有限,所以只需,encoding = "gbk",就不报错了。
还有一个函数我用错了,dic[i] = dic.get(i,0) +1 而不是 dic[i] = dic.get(dic[i], 0) + 1,哈哈哈
还有,在with open() 中,要用符号/,“C:/users/” ,或者r“C:users” ,或者r“C:\users\” ,因为如果不用r ,会把 符号 当成转义字符。