Python 停止在for循环中重复打印语句

Python 停止在for循环中重复打印语句,python,pycharm,Python,Pycharm,底部的print语句似乎在for循环中重复,我希望它们在代码运行时只打印一次。我确实试图在打印语句之前放一个break语句,认为这样做会起作用,但结果是语句根本无法打印 from string import punctuation from operator import itemgetter import operator fileName = input('Enter the file name') file = open(fileName, 'r') punc_translato

底部的print语句似乎在for循环中重复,我希望它们在代码运行时只打印一次。我确实试图在打印语句之前放一个break语句,认为这样做会起作用,但结果是语句根本无法打印

from string import punctuation

from operator import itemgetter

import operator

fileName = input('Enter the file name')

file = open(fileName, 'r')

punc_translator = str.maketrans({key: None for key in punctuation})

documentFile = str(file.read()).translate(punc_translator).lower()

print(documentFile)

alphabetCount = {

"a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0, "g": 0, "h": 0, "i": 0, "j": 0, "k": 0, "l": 0,

"m": 0, "n": 0, "o": 0, "p": 0, "q": 0, "r": 0, "s": 0, "t": 0, "u": 0, "v": 0, "w": 0, "x": 0,

"y": 0, "z": 0

}

totalWords = 0

totalDistinctWords = 0

for ch in documentFile:
   if ch != ' ':
   alphabetCount[ch] += 1
   allWords = documentFile.split(' ')
   wordsCountDict = dict()
   for word in allWords:
     totalWords += 1
     if word in wordsCountDict.keys():
         wordsCountDict[word] += 1
     else:
         wordsCountDict[word] = 1
         totalDistinctWords += 1

    print(totalWords)
    print(totalDistinctWords)

    sortedWordsCount = sorted(wordsCountDict.items(), key=operator.itemgetter(1), reverse=True)

    sortedCharactersCount = sorted(alphabetCount.items(), key=operator.itemgetter(1),reverse=True)

    print('The summary of document: ')

    print("Total words is: " + str(totalWords))

    print(totalDistinctWords)

    print('Most Frequent Characters:')

    print(sortedCharactersCount)

    print('Most Frequent Words:')

    print(sortedWordsCount)
这是当前的输出

查看缩进。 Python使用缩进来表示代码块

如果您想打开一个新的代码块,整个代码块应该在前面一个选项卡上

在您的情况下,最后的打印进入for循环。将它们向后移动一个选项卡以从循环中移除

在此处查看此语句后的逻辑:

如果ch!='':


您没有在此语句上执行任何代码。

您能提供运行此代码时发生的输出吗?那么预期的输出呢?好吧,你的缩进是乱七八糟的<代码>如果ch!='':后面应该跟一行(或多行),缩进比条件多。因此,我猜您的打印在for块中。此外,请检查您是否在缩进中混合制表符和空格。@12944qwerty输出基本上是打印语句的值,但它们只是重复。这些值是正确的,但我只是不希望它们重复。顺便说一句,这里通常不欢迎截图。看见