python統計語周波数

2126 ワード

一、reライブラリを用いて識別する
1、コード
import re,collections  
def get_words(file):  
    with open (file) as f:  
        words_box=[]  
        for line in f:                           
            if re.match(r'[a-zA-Z0-9]*',line):#        
                words_box.extend(line.strip().split())                 
    return collections.Counter(words_box)  
print(get_nums('emma.txt')+get_nums('    .txt'))  

2、参考
python-10行のコードは語周波数の統計pythonをやり遂げます:過去の英語の4、6級の答案用紙の単語の語周波数を統計します
二、Wordcloud点群ライブラリの使用
1、コード
#Wordcloud       
# _*_ coding:utf-8 _*_
from wordcloud import WordCloud
import matplotlib.pyplot as plt

f = open('txt/AliceEN.txt',encoding='UTF-8').read()
wordcloud = WordCloud(background_color="white",width=1000, height=860, margin=2).generate(f)
wordcloud.to_file('test.png')

plt.imshow(wordcloud)
plt.axis("off")
plt.show()
#Wordcloud          ,    jieba    
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS
import jieba

#       
backgroud_Image = plt.imread("love.jpg")
#           
text_from_file_with_apath = open("teng.txt",encoding='UTF-8').read()
#   jieba             
wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all=True)
wl_space_split = " ".join(wordlist_after_jieba)
my_wordcloud = WordCloud(
    background_color='white',    #       
    mask=backgroud_Image,        #       
    max_words=3000,              #          
    stopwords=STOPWORDS,         #      
    font_path='simfang.ttf',#       ,          
    max_font_size=40,            #        
    random_state=300,            #             ,         
    scale=5,
    width=16000,
    height=8000
    ).generate(wl_space_split)

#           
image_colors = ImageColorGenerator(backgroud_Image)
my_wordcloud.recolor(color_func=image_colors)
#         
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

2、参考
Python語雲wordcloud 15分入門と進級