2017-02-24 5 views
0

txtファイルのテキストからバイグラムの頻度を見つけようとしています。これまでのところ、それは動作しますが、それは数字をカウントし、symbols.Hereは私が持っているコードです:!。?Python-ビッグラム周波数の数字と記号を無視する

import nltk 
from nltk.collocations import * 
import prettytable 




file = open('tweets.txt').read() 
tokens = nltk.word_tokenize(file) 


pt = prettytable.PrettyTable(['Words', 'Counts']) 
pt.align['Words'] = 'l' 
pt.align['Counts'] = 'r' 



bgs = nltk.bigrams(tokens) 
fdist = nltk.FreqDist(bgs) 

for row in fdist.most_common(100): 
    pt.add_row(row) 
print pt 


Below is the code output: 
+------------------------------------+--------+ 
| Words        | Counts | 
+------------------------------------+--------+ 
| ('https', ':')      | 1615 | 
| ('!', '#')       | 445 | 
| ('Thank', 'you')     | 386 | 
| ('.', '``')      | 358 | 
| ('.', 'I')       | 354 | 
| ('.', 'Thank')      | 337 | 
| ('``', '@')      | 320 | 
| ('&', 'amp')      | 290 | 

のような、、、:)数字、記号を(無視する方法はありますか?テキストはつぶやきなので、#と@を除いて数字と記号は無視します。

答えて

0

bigramsのfdistは、バイグラムタプルとカウント整数を含むタプルのタプルです。バイグラムのタプルにアクセスし、バイグラムのカウントに加えて必要なものだけを保持します。これを試してみてください:

import nltk 
from nltk.probability import FreqDist 
from nltk.util import ngrams 
from pprint import pprint 

def filter_most_common_bigrams(mc_bigrams_counts): 
    filtered_mc_bigrams_counts = [] 
    for mc_bigram_count in mc_bigrams_counts: 
     bigram, count = mc_bigram_count 
     #print (bigram, count) 
     if all([gram.isalpha() for gram in bigram]) or bigram[0] in "#@" and bigram[1].isalpha(): 
      filtered_mc_bigrams_counts.append((bigram, count)) 
    return tuple(filtered_mc_bigrams_counts) 

text = """Is there a way to ignore numbers and symbols (like !,.,?,:)? 
Since the text are tweets, I want to ignore numbers and symbols, except for the #'s and @'s 
https: !# . Thank you . `` 12 hi . 1st place 1 love 13 in @twitter # twitter""" 

tokenized_text = nltk.word_tokenize(text) 
bigrams = ngrams(tokenized_text, 2) 
fdist = FreqDist(bigrams) 
mc_bigrams_counts = fdist.most_common(100)  
pprint (filter_most_common_bigrams(mc_bigrams_counts)) 

コードの重要な部分がある:

if all([gram.isalpha() for gram in bigram]) or bigram[0] in "#@" and bigram[1].isalpha(): 
    filtered_mc_bigrams_counts.append((bigram, count)) 

これは、バイグラムのすべての1グラムが最初のバイグラムは#や@記号であること、あるいは、文字であるかということをチェック第2のバイグラムは文字で構成されています。これらの条件を満たすものだけを追加し、バイグラムのfdist数を含むタプル内に追加します。

結果:

((('to', 'ignore'), 2), 
(('and', 'symbols'), 2), 
(('ignore', 'numbers'), 2), 
(('numbers', 'and'), 2), 
(('for', 'the'), 1), 
(('@', 'twitter'), 1), 
(('Is', 'there'), 1), 
(('text', 'are'), 1), 
(('a', 'way'), 1), 
(('Thank', 'you'), 1), 
(('want', 'to'), 1), 
(('Since', 'the'), 1), 
(('I', 'want'), 1), 
(('#', 'twitter'), 1), 
(('the', 'text'), 1), 
(('are', 'tweets'), 1), 
(('way', 'to'), 1), 
(('except', 'for'), 1), 
(('there', 'a'), 1))