fo= open('C:\\Users\Administrator\Desktop\zz.txt','r',encoding="utf-8") #从同一目录下读取文件
strgc = fo.read() #小写
fo.close()
print(strgc)
seq ='.,'
for ch in seq:
strgc=strgc.replace(ch," ") #用for循环replace函数将.和,替换成空格
print(strgc)
strList = strgc.split() #拆分
print(len(strList),strList) #分隔一个一个单词并统计英文单词个数
strSet = set(strList) #将列表转化成集合
exclude={"and","if","a","or","in","the"}
strSet=strSet-exclude #去掉排除语法型词汇,代词、冠词、连词等无语义词
print(strSet)
strDict={}
for word in strSet: #再将集合转化成字典来统计每个单词出现次数
strDict[word] = strList.count(word) #只有列表可以统计
print(len(strDict),strDict)
wclist =list(strDict.items()) #以列表返回可遍历的(键, 值) 元组数组
wclist.sort() #简单排序
print(strDict.items())
#def takeSecond(elem): #定义函数
# x=elem[1]
# return x
#wclist.sort(key=takeSecond,reverse=True) #排序,默认升序,reverse=true降序 法①
wclist.sort(key=lambda x:x[1],reverse=True) #方法② 用lambda函数排序
print(wclist)
for i in range(20): #输出前20个
print(wclist[i])
![](https://img2018.cnblogs.com/blog/1479619/201810/1479619-20181015095746914-1147045419.png)
import jieba
fo = open ('C:\\Users\Administrator\Desktop\\xs.txt', 'r', encoding='utf-8')
x = fo.read ()
fo.close ()
print (x)
sep = ',。?!;:“”‘’-——<_/>'
for en in sep:
x = x.replace (en, '')
zhaung = list (jieba.cut_for_search (x))
strSet = set (x)
# print(len(strSet), strSet)
strDict = dict ()
for word in strSet:
strDict[word] = x.count (word)
# print(len(strDict), strDict)
wcList = list (strDict.items ())
# print(wcList)
wcList.sort (key=lambda x: x[1], reverse=True)
# print(wcList)
for i in range (20):
print (wcList[i])
![](https://img2018.cnblogs.com/blog/1479619/201810/1479619-20181015110542059-934864989.png)
![](https://img2018.cnblogs.com/blog/1479619/201810/1479619-20181015110554364-1787452546.png)