比如在中文分词前,将中文逗号、中文句号、中文冒号、中文引号,英文空格替换为空字符。 replace方法 第6-7行代码实现替换功能。 import jieba d = {} with open("sgld.txt","r",encoding ="utf-8") as f: lssgld = f.readlines() for word in lssgld: word = word.replace(',','').replace('。','').replace('“','').replace('”','').replace(':','').replace(' ','').replace('\n','') wo = jieba.lcut(word) for w in wo: d[w] = d.get(w,0) + 1 ls = list(d.items()) #要理解这行代码 ls.sort(key=lambda x:x[1], reverse = True) for j in range(5): print(ls[j][0],end='、') for循环的方法 第7-9 行代码实现替换功能。 import jieba #导入中文分词库,这是必考点 with open("sgld.txt","r",encoding ="utf-8")as f: #使用with语句以只读方式打开文件 lssgld = f.readlines() #按行读取文件构建lssgld列表 d = {} #定义空字典 for ls in lssgld: ls = ls.replace("\n","") #数据清洗:去掉每一行最后的换行符 for c in "。,:”“ ": #中文分词前,将中文逗号、中文句号、中文冒号、中文引号,英文空格替换为空字符 ls = ls.replace(c, "") #使用字符串函数replace将 wordlist = jieba.cut(ls) #对每行进行中文分词 for word in wordlist: d[word] = d.get(word,0) + 1 #构建字典 ls = list(d.items()) ls.sort(key=lambda x:x[1], reverse = True) #列表排序 for i in range(5): a = ls[i][0] print("{}".format(a),end = "、") #出现次数前5的词 显然,for循环的方法更为简洁。