2014-01-14 2 views
15

から数え言葉は、私は次のコードでtxtファイルの単語をカウントしていますtxtファイルプログラム

>>> 
goat {'goat': 2, 'cow': 1, 'Dog': 1, 'lion': 1, 'snake': 1, 'horse': 1, '': 1, 'tiger': 1, 'cat': 2, 'dog': 1} 

を私はしたいです次のように出力:

word wordcount 
goat 2 
cow  1 
dog  1..... 

はまた、私は出力()に余分な記号を取得しています。これをどうやって削除できますか?

+0

は、[書式設定文字列](http://docs.python.org/2/library/string.html#formatspecを見てください)。 –

答えて

34

面白いシンボルは、UTF-8 BOM (Byte Order Mark)です。それらを取り除くために、適切なエンコーディング(私はあなたは、Python 3にしていると仮定しています)を使用してファイルを開く:

from collections import Counter 
wordcount = Counter(file.read().split()) 

file = open(r"D:\zzzz\names2.txt", "r", encoding="utf-8-sig") 

をさらに、カウントのために、あなたはcollections.Counterを使用することができますそれらを表示するだけでなく簡単です:

>>> for item in wordcount.items(): print("{}\t{}".format(*item)) 
... 
snake 1 
lion 2 
goat 2 
horse 3 
1
import sys 
file=open(sys.argv[1],"r+") 
wordcount={} 
for word in file.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 
for key in wordcount.keys(): 
    print ("%s %s " %(key , wordcount[key])) 
file.close(); 
+0

あなたのpythonバージョンは何ですか? – duck

+0

私は完全な例を与えてくれましたか? – duck

+0

http://www.compileonline.com/execute_python_online.phpで有効性の例を確認できます – duck

29
#!/usr/bin/python 
file=open("D:\\zzzz\\names2.txt","r+") 
wordcount={} 
for word in file.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 
for k,v in wordcount.items(): 
    print k, v 
2

graphLabを使用している場合は、この関数を使用できます。それは本当に強力である

products['word_count'] = graphlab.text_analytics.count_words(your_text) 
0
FILE_NAME = 'file.txt' 

wordCounter = {} 

with open(FILE_NAME,'r') as fh: 
    for line in fh: 
    # Replacing punctuation characters. Making the string to lower. 
    # The split will spit the line into a list. 
    word_list = line.replace(',','').replace('\'','').replace('.','').lower().split() 
    for word in word_list: 
     # Adding the word into the wordCounter dictionary. 
     if word not in wordCounter: 
     wordCounter[word] = 1 
     else: 
     # if the word is already in the dictionary update its count. 
     wordCounter[word] = wordCounter[word] + 1 

print('{:15}{:3}'.format('Word','Count')) 
print('-' * 18) 

# printing the words and its occurrence. 
for (word,occurance) in wordCounter.items(): 
    print('{:15}{:3}'.format(word,occurance)) 
Word   Count 
    ------------------ 
    of    6 
    examples   2 
    used    2 
    development  2 
    modified   2 
    open-source  2 
0
#!/usr/bin/python 
file=open("D:\\zzzz\\names2.txt","r+") 
wordcount={} 
for word in file.read().split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 

for k,v in wordcount.items(): 
    print k,v 
file.close(); 
+2

いくつかの説明を追加してください。 –

関連する問題