import string
def read_file(file):
with open(file, 'r', encoding='utf-8') as f:
return f.read()
def classify_char(txt):
upper, lower, digit, a_space, other = 0, 0, 0, 0, 0
for ch in txt:
if ch.islower():
lower = lower + 1
elif ch.isupper():
upper = upper + 1
elif ch.isnumeric():
digit = digit + 1
elif ch==" ":
a_space = a_space + 1
else:
other = other + 1
return upper, lower, digit, a_space, other
if name == 'main':
filename = input() # 读入文件名
text = read_file(filename)
classify = classify_char(text)
print('大写字母{}个,小写字母{}个,数字{}个,空格{}个,其他{}个'.format(*classify))
__name__
方法是python中的一个内置函数,记录的值就是一个字符串
如果是在当前文件中执行,记录的值就是__main__
在test1文件中编写
print(__name__) #输出__manin__说明此时是在本文件中执行
输出结果:
C:\Users\qun\AppData\Local\Programs\Python\Python37\python.exe C:/Users/qun/Desktop/python封装项目/test1.py
__main__
如果是在另外的py文件中执行,记录的值就是模块名
在test2文件中编写
import test1 #输出的是文件文件名,说明是在其他文件中导入执行的
输出结果:
C:\Users\qun\AppData\Local\Programs\Python\Python37\python.exe C:/Users/qun/Desktop/python封装项目/test2.py
test1
代码没有发现明显的问题
import string
def read_file(file):
with open(file, 'r', encoding='utf-8') as f:
return f.read()
def classify_char(txt):
upper, lower, digit, a_space, other = 0, 0, 0, 0, 0
for ch in txt:
if ch.islower():
lower = lower + 1
elif ch.isupper():
upper = upper + 1
elif ch.isnumeric():
digit = digit + 1
elif ch==" ":
a_space = a_space + 1
else:
other = other + 1
return upper, lower, digit, a_space, other
filename = input() #读入文件名
text = read_file(filename)
classify = classify_char(text)
print('大写字母{}个,小写字母{}个,数字{}个,空格{}个,其他{}个'.format(*classify))
注意缩进,注意输入的文件名是否正确。