pythontextenchant

Incorrect output using count on text file spelling errors


I am trying to count the number of spelling errors in a number of text files in a directory, using python and enchant. This is my code:

for file in os.listdir(path): 
    if file.endswith(".txt"):
       f = open(file, 'r', encoding = 'Latin-1')
       text = f.read()
       chkr.set_text(text)
       count = 0
       for err in chkr:
           count += 1
           print (file, count)

However instead of giving me the count of all total errors in a file, I seem to be getting a cumulative count with files printed multiple times, e.g.:

ca001_mci_07011975.txt 1
ca001_mci_07011975.txt 2
ca001_mci_07011975.txt 3
ca001_mci_07011975.txt 4
ca001_mci_07011975.txt 5
ca001_mci_07011975.txt 6
ca001_mci_07011975.txt 7
ca001_mci_07011975.txt 8

There is only one file called ca001_mci_07011975 in the directory, so I was expecting:

ca001_mci_07011975.txt 8

I can't for the life of me figure out what I've done wrong! Any help very much appreciated.


Solution

  • try this:

    for file in os.listdir(path): 
        if file.endswith(".txt"):
           f = open(file, 'r', encoding = 'Latin-1')
           text = f.read()
           chkr.set_text(text)
           errors_count = 0
           for err in chkr:
               errors_count += 1
           print (file, errors_count )
    

    Problem is, you're actually printing for each loop iteration. Also, I changed count variable to something more relevant.