[python] Word count from a txt file program

I am counting word of a txt file with the following code:

#!/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
print (word,wordcount)
file.close();

this is giving me the output like this:

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

but I want the output in the following manner:

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

Also I am getting an extra symbol in the output (). How can I remove this?

This question is related to python

The answer is


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

#!/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();

The funny symbols you're encountering are a UTF-8 BOM (Byte Order Mark). To get rid of them, open the file using the correct encoding (I'm assuming you're on Python 3):

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

Furthermore, for counting, you can use collections.Counter:

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

Display them with:

>>> for item in wordcount.items(): print("{}\t{}".format(*item))
...
snake   1
lion    2
goat    2
horse   3

If you are using graphLab, you can use this function. It is really powerfull

products['word_count'] = graphlab.text_analytics.count_words(your_text)

Below code from Python | How to Count the frequency of a word in the text file? worked for me.

 import re
    frequency = {}
    #Open the sample text file in read mode.
    document_text = open('sample.txt', 'r')
    #convert the string of the document in lowercase and assign it to text_string variable.
    text = document_text.read().lower()
    pattern = re.findall(r'\b[a-z]{2,15}\b', text)
    for word in pattern:
         count = frequency.get(word,0)
         frequency[word] = count + 1
     frequency_list = frequency.keys()
     for words in frequency_list:
         print(words, frequency[words])

OUTPUT: enter image description here


#!/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

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();

you can do this:

file= open(r'D:\\zzzz\\names2.txt')
file_split=set(file.read().split())
print(len(file_split))

print("sorted counting values:-")
from collections import Counter

fname = open(filename)

fname = fname.read()

fsplit = fname.split()

user  = Counter(fsplit)

for i,v in sorted(user.items()):

   print((v,i))