python初学者 也没怎么被教 希望指导一下如何完善这个代码
以及要怎么学习谢谢
import jieba
list_names=["的","地","得"]
list1=[]
count = {}
with open("sefile.txt", "r", encoding="utf-8") as f:
txt=f.read()
words=jieba.cut(txt)
for word in words:
if word in list_names:
list1.append(word)
count[word]=count.get(word, 0)+1
kind=len(set(list1))
print("sefile.txt文件中结构助词的种类有: {:>5}".format(kind))
items=list(count.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(kind):
var, number=items[i]
print('文件中"{0}"字出现次数为{1:>5}'.format(var, number))
解释:
第一个空需要填写文件打开模式,题目中要求只读模式,因此应该填写"r"。
第二个空需要对文件内容进行读取操作,可以使用read()方法来实现,因此代码应该为txt=f.read()。
第三个空需要使用jieba库对文本进行分词,可以使用jieba.cut()方法来获取分词结果,因此代码应该为words=jieba.cut(txt)。
第四个空需要判断当前处理的单词是否为结构助词,可以使用in关键字和列表list_names来实现,因此代码应该为if word in list_names:。
第五个空需要将符合条件的单词添加到list1列表中,因此应该填写list1.append(word)。
第六个空需要统计每个结构助词出现的次数,可以使用字典count来实现,因此代码应该为count[word]=count.get(word, 0)+1。
第七个空需要计算不同的结构助词种类数,可以使用set()函数对list1去重后获取其长度,因此代码应该为kind=len(set(list1))。
第八个空需要将字典count转换为元组列表items,可以使用count.items()方法来实现,因此代码应该为items=list(count.items())。
第九个空需要按照结构助词出现次数从大到小进行排序,可以使用sort()方法和lambda表达式来实现,因此代码应该为items.sort(key=lambda x:x[1], reverse=True)。
第十个空需要输出每个结构助词出现的次数,需要使用format()方法来格式化输出,其中:>5表示右对齐并占用5个字符宽度,因此代码应该为print('文件中"{0}"字出现次数为{1:>5}'.format(var, number))。
https://blog.csdn.net/weixin_39708636/article/details/110044187