2017-08-06 47 views
0

我需要製作一個程序來讀取文本文件並打印出有多少元音和輔音。我製作一個文本文件進行測試,其中唯一的內容是「這是一個測試」。然而總是輸出它:計算文件中的元音和輔音(Python)

輸入要檢查的文件:test.txt的

元音的數量爲:1

輔音的數量:0

fileName = input("Enter the file to check: ").strip() 

infile = open(fileName, "r") 


vowels = set("A E I O U a e i o u") 
cons = set("b c d f g h j k l m n p q r s t v w x y z B C D F G H J K L M N P Q R S T V W X Y Z") 

text = infile.read().split() 


countV = 0 
for V in text: 
    if V in vowels: 
     countV += 1 

countC = 0 
for C in text: 
    if C in cons: 
     countC += 1 

print("The number of Vowels is: ",countV,"\nThe number of consonants is: ",countC) 

如果有是一個更好的方式來輸入元音和缺點的值我也想知道,因爲當我嘗試用戶.lower()將文件中的所有內容轉換爲小寫時,出現錯誤.....

+0

因爲你計算空間以及? –

回答

2
  1. set("A E I O U a e i o u")將導致{' ', 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}。如果你會注意到,這個空間也被考慮在內。你需要刪除字母之間的空格。

  2. infile.read().split()將根據空白分割,所以你得到一個單詞列表。然後,您繼續遍歷,並嘗試字母之間的成員資格比較。這不適合你。

  3. 您不需要迭代兩次。一次就夠了。


這是你的代碼的清理版本。

vowels = set("AEIOUaeiou") 
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ") 

countV = 0 
countC = 0 
for c in infile.read(): 
    if c in vowels: 
     countV += 1 
    elif c in cons: 
     countC += 1 

作爲改進,考慮使用collections.Counter。它爲你計數,你只需要總結一下計數。

import collections 
c = collections.Counter(infile.read()) 

countV = sum(c[k] for k in c if k in vowels) 
countC = sum(c[k] for k in c if k in cons) 
+0

謝謝@COLDSPEED幫助。我做了稍微不同,但擺脫.split()和刪除空格是一個很大的幫助。我認爲這些套不會重複自己?那麼這不是說它會計算空間而不是顯示0作爲結果嗎? – PyPunk

+1

@EvanH它計數空格一次,但仍然計數。除非你刪除了元音和字符,否則你的空間會被錯誤地計算爲元音和字符。 –

+0

@COLDSPEED明白了。非常感謝您的幫助和快速響應! – PyPunk