【发布时间】:2021-05-22 15:48:12
【问题描述】:
我试图转换一个程序,该程序接受用户字符串输入并定义字符串有多少个小写、大写、数字和字符。进入读取文本文件并输出小写/大写/数字/和字符的程序。我的大部分程序都像打印输出一样完成,但我无法弄清楚为什么我的 .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()
【问题讨论】:
-
你打电话给
readline而不是readlines。 -
请格式化代码 - 选择它并输入
ctrl-k。 ..Formatting help...Formatting sandbox