我正在尝试添加位置,名称,教室,直到空白从文件使用:
Get-Content in.txt | python school.py
in.txt例子:
supervisor
Jack
1a
1b
2a
supervisor_list = []
supervisor_dict = {}
def user_type():
check_who = input()
if check_who == "supervisor":
name = input()
check_class = input()
supervisor_dict["User"] = check_who
supervisor_dict["Name"] = name
supervisor_dict["School_class"] = check_class
check_class = input()
while not check_class.isspace():
supervisor_dict["School_class"] += " " + check_class
supervisor_list.append(supervisor_dict)
check_class = input()
你能告诉我我做错了什么吗?谢谢!check_class.isspace()
检查字符串是否为空格,如"。如果您想检查一行是否为空,只需使用check_class == ''
;如果您想接受带有空格的行为空行,则使用check_class.strip() == ''
代码check_class.isspace()
将检查字符串是否为空"如果你想检查一行是空的,你可以尝试check_class == ''
,如果你想检查字符串是否包含任何空格在它比(' ' in check_class) == True
首先应该运行函数。如果您希望用户通过命令行输入数据,这将是一个可能的解决方案:
supervisor_list = []
supervisor_dict = {}
stop_character = ""
def user_type():
check_who = input()
if check_who == "supervisor":
name = input()
check_class = input()
supervisor_dict["User"] = check_who
supervisor_dict["Name"] = name
supervisor_dict["School_class"] = check_class
while True:
check_class = input()
if check_class == stop_character:
break
supervisor_dict["School_class"] += " " + check_class
supervisor_list.append(supervisor_dict)
user_type()
您可能希望它像这样写
supervisor_list = []
supervisor_dict = {}
def user_type():
check_who = input("Enter user type: ")
if check_who == "supervisor" or check_who == "Supervisor":
name = input("Enter name: ")
check_class = input("Enter class: ")
supervisor_dict["User"] = check_who
supervisor_dict["Name"] = name
supervisor_dict["School_class"] = check_class
while not check_class.isspace():
supervisor_dict["School_class"] += " " + check_class
check_class = input("Enter class: ")
supervisor_list.append(supervisor_dict)
return supervisor_list
你可以修改你的终端参数,让它有一些可以识别的东西,否则你只是用完了行。
这将在末尾或空白行处停止。
(Get-Content in.txt) + '' | python school.py
school.py
supervisor_list = []
def user_type():
supervisor_dict = {
'User': input(),
'Name': input(),
'School_class': input()
}
if supervisor_dict["User"] == "supervisor":
while (check_class := input()):
supervisor_dict["School_class"] += ' ' + check_class
supervisor_list.append(supervisor_dict)
user_type()
print(supervisor_list)
输出:
[{'User': 'supervisor', 'Name': 'Jack', 'School_class': '1a 1b 2a'}]
另外,如果我们不能改变输入,让我们继续下去,直到错误,或空白行:
Get-Content in.txt | python school.py
school.py
supervisor_list = []
def user_type():
supervisor_dict = {
'User': input(),
'Name': input(),
'School_class': input()
}
if supervisor_dict["User"] == "supervisor":
while True:
try:
if not (check_class := input()) : break
except EOFError : break
supervisor_dict["School_class"] += ' ' + check_class
supervisor_list.append(supervisor_dict)
user_type()
print(supervisor_list)