infile=open('test.txt')
outfile =open('formatedtest.txt','w')
for line in infile:
line =line.rstrip('\n')
unicodeline=unicode(line,'gb2312')
length=len(unicodeline)
i=0
while i<length:
#print unicodeline[i]
d=unicodeline[i].encode('utf-8')
outfile.write(d)
outfile.write(' ')
i+=1
这里是 对汉字后面加一个空格,当训练的样本是按照 char 来分词的时候,可以这样做。
下面是 按照 jieba 分词写的:
就是对按照汉语的词分开,比如 中国的高山很巍峨。 就会分为《中国 的 高山 很 巍峨 。》
import jieba
f=open("hello.txt","rb")
f1=open("hello1.txt","w",encoding='utf-8')
global line_old
for line in f:# 读取每一行
line_uni = line.decode('utf-8')
line_uni.strip()
# print(line_uni)
# print(line_uni[-3])
# split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(list)
line_new = seg_list = jieba.cut(line_uni)
line_new =" ".join(line_new)
f1.writelines(line_new)
f.close()
f1.close()