Skip to content Skip to sidebar Skip to footer

Python - Find The Occurrence Of The Word In A File

I am trying to find the count of words that occured in a file. I have a text file (TEST.txt) the content of the file is as follows: ashwin programmer india amith programmer india

Solution 1:

Use the update method of Counter. Example:

from collections import Counter

data = '''\
ashwin programmer india
amith programmer india'''

c = Counter()
for line in data.splitlines():
    c.update(line.split())
print(c)

Output:

Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})

Solution 2:

from collections import Counter;
cnt = Counter ();

for line inopen ('TEST.txt', 'r'):
  for word in line.split ():
    cnt [word] += 1print cnt

Solution 3:

You're iterating over every line and calling Counter each time. You want Counter to run over the entire file. Try:

from collections import Counter

withopen("TEST.txt", "r") as f:
    # Used file context read and save into contents
    contents = f.read().split()
print Counter(contents)

Solution 4:

Using a Defaultdict:

from collections import defaultdict 

defread_file(fname):

    words_dict = defaultdict(int)
    fp = open(fname, 'r')
    lines = fp.readlines()
    words = []

    for line in lines:
        words += line.split(' ')

    for word in words:
        words_dict[word] += 1return words_dict

Solution 5:

FILE_NAME = 'file.txt'

wordCounter = {}

withopen(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 notin wordCounter:
        wordCounter[word] = 1else:
        # if the word is already in the dictionary update its count.
        wordCounter[word] = wordCounter[word] + 1print('{: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))

Post a Comment for "Python - Find The Occurrence Of The Word In A File"