Finding the occurrence of a specific character from a text file - Python

Viewed 336

I want to write a function that takes a file name and a list as arguments and reads the text within the corresponding file, then creates a dictionary whose keys are the characters of the provided list, and the values are the counts of these characters within the text. If the file does not exist, then the function returns an empty dictionary. For example:

sample.txt
This is an example sentence
This is yet another sentence

Here is the code that I've written so far:

def text2dict(filename, characters):
   count_word = dict()
   for char in characters:
      count_word[char] = 0
   with open(filename) as input_text:
       text = input_text.read()
       words = text.lower().split()
       for word in words:
          _word = word.strip('.,:-)()')
          if word in count_word:
            count_word[_word] += 1
   return count_word
file_name = "sample.txt"
list_char = ["a", "b", "c", "t"]
text2dict(file_name, list_char)
      

Expected Output:

{'a':3, 'b':0, 'c':2, 't':6}

The output I got:

{'a': 0, 'b': 0, 'c': 0, 't': 0}
3 Answers

You can use "".count() for that. Also there is no need to pre-fill the dictionary anymore, as we are not using iadd.

   def text2dict(filename, characters):
       count_letters = dict()
       
       with open(filename) as input_text:
           text = input_text.read()
           for k in characters:
               count_letters[k] = text.count(k)
       return count_letters

With this you get the expected result

>>> file_name = r"sample.txt"
>>> list_char = ["a", "b", "c", "t"]
>>> print(text2dict(file_name, list_char))
{'a': 3, 'b': 0, 'c': 2, 't': 6}

You are checking if a word is existing in the dictionnary, but the dictionnary only contains letters.

Spoiler:

if you want a working version right away:

def text2dict(filename, characters):
   count_word = dict()
   for char in characters:
      count_word[char] = 0
   with open(filename) as input_text:
       text = input_text.read()
       words = text.lower().split()
       for word in words:
            _word = list(word)
            for i in _word:
                if i in count_word:
                    count_word[i] += 1

   return count_word

You can use collections.Counter().

from collections import Counter
file = open('test.txt')
rows = [row.strip().replace(' ','').lower() for row in file] 
wanted = ["a", "b", "c", "t"]
finalDict = {letters:dict(Counter(r)).get(letters,0) for r in rows for letters in wanted}

output

{'a': 1, 'b': None, 'c': 1, 't': 4}

Shortened down all the way, for funnsies

from collections import Counter
finalDict = {letters:dict(Counter(r)).get(letters) for r in [row.strip().replace(' ','').lower() for row in open('test.txt')]  for letters in ["a", "b", "c", "t"]}
Related