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

2024-07-08 07:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

底部的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)

这是当前的输出

enter image description here


Tags: keyinimportfor语句operatorwordfile
1条回答
网友
1楼 · 发布于 2024-07-08 07:18:29

回顾你的缩进。 Python使用缩进来表示代码块

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

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

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

if ch != ' ':

您不能在此语句上执行任何代码

相关问题 更多 >

    热门问题