def showCounts(fileName):
lineCount = 0
wordCount = 0
numCount = 0
comCount = 0
dotCount = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
lineCount += 1
wordCount += len(words)
for word in words:
# ###text = word.translate(string.punctuation)
exclude = set(string.punctuation)
text = ""
text = ''.join(ch for ch in text if ch not in exclude)
try:
if int(text) >= 0 or int(text) < 0:
numCount += 1
# elif text == ",":
# comCount += 1
# elif text == ".":
# dotCount += 1
except ValueError:
pass
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
print("Number count: " + str(numCount))
print("Comma count: " + str(comCount))
print("Dot count: " + str(dotCount) + "\n")
基本上,它會顯示的行數和文字的數量,但我不能得到它顯示的數量數字,逗號和點。我讀了一個文件,用戶輸入,然後顯示大量的行和單詞,但由於某種原因,它表示數字逗號和點數爲0。我評論了它給我帶來麻煩的部分。如果我刪除逗號,那麼我只是得到一個錯誤。謝謝你們Python的 - 如何打印數字,句號和逗號的數量在文件
嗯。奇。它的數字點和逗號是正確的,但它提供的行數和單詞數量遠遠高於他們實際上的數字...... – TommyConnor
Are you sure?它在我上面的演示中得到了正確的... –
對不起,我誤打錯了。數字逗號和點是好的 - 非常感謝!由於某種原因,我有9行,但它說我有98,我可能有20個字,但它說我有304 ... – TommyConnor