python-найти вхождение слова в файл
Я пытаюсь найти количество слов, которые произошли в файле. У меня есть текстовый файл (TEST.txt) содержимое файла выглядит следующим образом: 
ashwin programmer india
amith programmer india
результат, который я ожидаю:
{ 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1}
код, который я использую:
for line in open(TEST.txt,'r'):
    word = Counter(line.split())
    print word
результат, который я получаю:
Counter({'ashwin': 1, 'programmer': 1,'india':1})
Counter({'amith': 1, 'programmer': 1,'india':1})
может ли кто-нибудь помочь мне? Спасибо заранее.
5 ответов
использовать update метод борьбы.  Пример:
from collections import Counter
data = '''\
ashwin programmer india
amith programmer india'''
c = Counter()
for line in data.splitlines():
    c.update(line.split())
print(c)
выход:
Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})
from collections import Counter;
cnt = Counter ();
for line in open ('TEST.txt', 'r'):
  for word in line.split ():
    cnt [word] += 1
print cnt
использование Defaultdict:
from collections import defaultdict 
def read_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] += 1
    return words_dict
вы повторяете каждую строку и вызываете счетчик каждый раз. Вы хотите, чтобы Counter пробежался по всему файлу. Попробуйте:
from collections import Counter
with open("TEST.txt", "r"):
    contents = f.read().split()
print Counter(contents)
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))