0

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.

4

1 回答 1

0

尝试这个:

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 )

问题是,您实际上是在为每个循环迭代打印。此外,我将count变量更改为更相关的内容。

于 2017-11-06T19:54:23.293 回答