Python词频对比并导入CSV文件
生活随笔
收集整理的這篇文章主要介紹了
Python词频对比并导入CSV文件
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
需要用到的停用詞庫我上傳到我的資源了,大家也可以自己去網(wǎng)上找!
本來是想把兩個(gè)詞頻統(tǒng)計(jì)放入一個(gè)CSV文件中,但是無奈向已經(jīng)存在的CSV文件中追加寫入數(shù)據(jù)只能在已經(jīng)存在的數(shù)據(jù)下面追加,也就是在同一列追加,不能另起一列添加數(shù)據(jù),哪位兄弟懟出來了,歡迎回復(fù)或私信!
import jieba import pandas as pd import csv import codecs # num=jieba.lcut("中國是一個(gè)偉大的國家") # jieba庫的測試 # print(num) # 計(jì)算機(jī)專業(yè)的-1.txt txt1=open("計(jì)算機(jī)專業(yè).txt").read() # 導(dǎo)入停用詞庫,過濾掉那些沒用的詞語,甚至都不是詞語,比如標(biāo)點(diǎn)符號,停用詞在我的資源中有保存 stopwords=[line.strip() for line in open("停用詞.txt").readlines()] words1=jieba.lcut(txt1) # print(words1) counts1={} for word1 in words1:if len(word1)==1:continueelse:counts1[word1]=counts1.get(word1,0)+1 items1=list(counts1.items()) items1.sort(key=lambda x:x[1],reverse=True) # 根據(jù)詞頻進(jìn)行降序排序 # print(items1) file_csv=open("計(jì)算機(jī)專業(yè)詞頻.csv",'w+',newline='') #添加newline='',可以刪除每行之間的空行 writer=csv.writer(file_csv) writer.writerow(["詞匯","詞頻"]) for data in items1:writer.writerow(data) file_csv.close() # 法學(xué)專業(yè)的-2.txt txt2=open("法學(xué)專業(yè).txt").read() words2=jieba.lcut(txt2) counts2={} for word2 in words2:if len(word2)==1:continueelse:counts2[word2]=counts2.get(word2,0)+1 items2=list(counts2.items()) items2.sort(key=lambda x:x[1],reverse=True) #print(items2) # dataframe=pd.DataFrame({'items1_name':items1,'items2_name':items2}) # dataframe.to_csv("test.csv") # file_csv=open('test.csv','a') file_csv=open("法學(xué)專業(yè)詞頻.csv",'w+',newline='') writer=csv.writer(file_csv) writer.writerow(["詞匯","詞頻"]) for data in items2:writer.writerow(data) file_csv.close()?
總結(jié)
以上是生活随笔為你收集整理的Python词频对比并导入CSV文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python程序练习题6.2
- 下一篇: Python中list、set和tupl