2017-09-15 4 views
0

Pythonのある列の文字列に単語が何回出現するかを数えるには?Pythonのある列に単語が何回出現するかを調べるには

file|context 
----|------- 
1 | Hello world 
2 | Round and round 

私は言葉の発生を計算したい:例えば

file| context   | word_count 
----|-----------------|--------------------- 
1 | Hello world  | {'hello':1,'world':1} 
2 | Round and round | {'round':2,'and':1} 

私は一日のためにそれに立ち往生してvalue_counts()とカウンタを使用することが試みられています。まだそれを理解することはできません。どんな助け?

ありがとうございます!

+0

どのようにCounterとvalue_counts()を使用しようとしましたか? –

+0

どのような種類のデータ構造を表示していますか?テキストテーブルの構文解析と 'pandas'データフレームのようなものについての作業については、非常に異なる回答が得られます。適切なタグを追加してください。おそらく( 'string'と' count'はここではあまり役に立ちません)。 – Blckknght

答えて

2

あなたは、分割された文字列の小文字バージョンにcollections.Counterを使用することができます。

from collections import Counter 

s = 'Round and round' 
counts = Counter(s.lower().split()) 
print(dict(counts)) 

出力:

 
{'and': 1, 'round': 2} 

次のあなたのデータを操作するためにこれを適応する必要があります。データ形式は、コンテキスト列がデータを仮定すると、7位から始まるので、固定幅フィールドを使用しているようだファイルから来ている:

with open('data') as f: 
    next(f) # skip the header 
    next(f) # skip the border 
    # print new header and border 

    for line in f: 
     counts = Counter(line[6:].lower().split()) 
     print('{} | {}'.format(line, dict(counts))) 

正しく出力列に数をフォーマットするために行うにはいくつかの作業があります。 1以下

+0

ありがとうございます。それは多くの助けになりました! – Lily

0

は、文字列に表示される回数ワードの数のカウントを与える

str = "Round and round" 
dict1={} 
for eachStr in str.split(): 
    if eachStr.lower() in dict1.keys(): 
     count = dict1[eachStr] 
     count = count + 1 
     dict1[eachStr.lower()] = count 
    else: 
     dict1[eachStr.lower()] = 1 
print dict1 

OUTPUT:

{'and': 1, 'round': 2} 
0

あなたは、この目的のためにPythonでビルド機能Counterを使用することができます。 Counterは異なり、大文字と小文字を検討しているため

In [5]: from collections import Counter 

In [6]: string = 'Hello world' 

In [9]: count = Counter(string.lower().split()) 

In [10]: print(dict(count)) 
{'world': 1, 'hello': 1} 

lowercaseに単語を変換します。

+1

ありがとうございます! – Lily

関連する問題