我正在尝试转换一个程序,该程序接受用户的字符串输入,并定义字符串包含多少小写、大写、数字和字符。输入一个读取文本文件并输出小写/大写/数字/和字符的程序。我将大部分程序作为打印输出,但我不明白为什么我的.readlines()不读取文件中的每一行并分析它们,而只是查看第一行
def countList( myList ):
if len(myList) == 0:
return 0
#variables
totalChars = 0
digitCount = 0
spaceCount = 0
alphaCount = 0
upperCase = 0
lowerCase = 0
notDigitOrAlphaOrSpace = 0
for ch in myList:
totalChars+=1
if ch.isdigit():
digitCount+=1
elif ch.isspace():
spaceCount+=1
if ch.isupper():
upperCase+=1
else:
lowerCase+=1
else:
notDigitOrAlphaOrSpace+=1
#output
print("Total characters:\t\t",totalChars)
print("Total digits:\t\t",digitCount)
print("Total spaces:\t\t",spaceCount)
print("\tAlpha upper:\t",upperCase)
print("\tAlpha lower:\t", lowerCase)
print("Not an alpha or digit or space:\t", notDigitOrAlphaOrSpace)
return totalChars
def main():
myFile = open('text.txt','r')
myList = myFile.readline()
# call our count the characters function
numChars = countList(myList)
if numChars > 0:
print("Your file was",numChars,"characters long")
else:
print("Your file had no characters.")
main()
调用file.readlines()而不是readline()来读取所有行
相关问题 更多 >
编程相关推荐