简体   繁体   English

使用文本文件拼写错误计数时输出不正确

[英]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. 我正在尝试使用python和附魔计算目录中多个文本文件中的拼写错误数量。 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, eg: 但是,我没有给我一个文件中所有错误的总数,而是获得了多次打印文件的累积计数,例如:

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的文件,因此我期望:

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. 任何帮助,非常感谢。

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. 另外,我将count变量更改为更相关的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM