我收到一条错误消息
回溯(最近一次调用最后一次):
文件“/Users/user/PycharmProjects/SSW-540/P8-hajayi.py”,第 34 行,位于
字母计数[ch] += 1
关键错误:'\n'
我还注意到打印语句正在重复,我认为这可能是因为它们位于 for 循环中。我不想让他们重蹈覆辙。
此外,“from operator import itemgetter”和“import Operator”中的 from 和 import 不会像第一次导入那样发出蓝色光。是因为我使用的python版本吗?我使用 python 3.6
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)