2 回答

TA貢獻1795條經驗 獲得超7個贊
第二個循環應該針對給定行中的每個字符。
試試這個:
ein = input("Please enter file name: ")
vowels = set("AEIOUaeoiu")
cons = set("BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwvyz")
num = set("1234567890")
count = 0
Vcount = 0
Ccount = 0
Ncount = 0
with open(ein) as ein_handle:
for line in ein_handle:
count += 1
for letter in line:
if letter in vowels:
Vcount += 1
elif letter in cons:
Ccount += 1
elif letter in num:
Ncount += 1
print("the file has", count, "lines.")
print("the file has", Vcount, "vowels.")
print("the file has", Ccount, "consonants.")
print("the file has", Ncount, "numerical characters.")
另外,在第二個循環內得到 0 (而不是行數)的主要原因是因為當第一個循環執行時,它會在每次迭代時更新讀取偏移位置,直到它結束。因此,當第二個循環開始時,它從文件末尾開始,無法讀取任何內容。

TA貢獻1803條經驗 獲得超6個贊
這是另一種方法:
import os
d,_ = os.path.split(__file__)
ein = input("Please enter file name: ")
vowels = "aeoiu"
cons = "bcdfghjklmnpqrstvwvyz"
num = "1234567890"
Vcount = 0
Ccount = 0
Ncount = 0
with open(d+"\\" + ein) as ein_handle:
lines = ein_handle.readlines()
for line in lines:
line = line.lower()
for v in vowels:
tmp = line
while v in tmp:
Vcount += 1
tmp = tmp[tmp.find(v)+1:]
for c in cons:
tmp = line
while c in tmp:
Ccount += 1
tmp = tmp[tmp.find(c)+1:]
for n in num:
tmp = line
while n in tmp:
Ncount += 1
tmp = tmp[tmp.find(n)+1:]
print("the file has",len(lines),"lines.")
print("the file has",Vcount,"vowels.")
print("the file has",Ccount,"consonants.")
print("the file has",Ncount,"numerical characters.")
添加回答
舉報