我使用Python创建了一个程序,它本质上是一个计算术语的字典。该程序使用户能够使用各自的定义添加自己的术语,程序将保存它,但仅限于该会话,使用户无用。
如何使程序保存用户的术语和定义,以便在程序关闭时不会丢失?老实说,我不知道该怎么做。这只是一个CLI程序,我没有把它变成可执行文件,如果这对你有帮助的话。
terms = {"ALU":"Arithmetic Logic Unit", "CPU":"Central Processing Unit", "GPU":"Graphics Processing Unit"}
def print_menu():
print('Computing Terms')
print()
print('0. Quit')
print('1. Look Up a Term')
print('2. Add a Term')
print('3. Redefine a Term')
print('4. Delete a Term')
print('5. Display All Terms')
while True:
print_menu()
print()
choice = int(input('Choice: '))
if choice == 0:
break
elif choice == 1:
print('\n')
term = input('Type in a term you wish to see: ')
if term in terms:
definition = terms[term]
print('\n')
print(term, '-', definition, '\n')
print()
print('----------------------------------------------------------------')
print()
print()
else:
print('This term does not exist. Try adding it instead.\n')
print()
print('----------------------------------------------------------------')
print()
print()
elif choice == 2:
print('\n')
term = input('What term would you like to add?: ')
if term not in terms:
print('\n')
definition = input('What\'s the definition?: ')
terms[term] = definition
print('\n')
print(term, 'has been added.\n')
print()
print('----------------------------------------------------------------')
print()
print()
else:
print('\n')
print('Term already exists, try redefining it instead.\n')
print()
print('----------------------------------------------------------------')
print()
print()
elif choice == 3:
print('\n')
term = input('Which term do you want to redefine?: ')
if term in terms:
definition = input('What\'s the new definition?: ')
terms[term] = definition
print('\n')
print(term, 'has been redefined.\n')
print()
print('----------------------------------------------------------------')
print()
print()
else:
print('\n')
print('That term doesn\'t exist, try adding it instead.')
print()
print('----------------------------------------------------------------')
print()
print()
elif choice == 4:
print('\n')
term = input('Which term would you like to delete?: ')
if term in terms:
del terms[term]
print('\n')
print('The term has been deleted.\n')
print()
print('----------------------------------------------------------------')
print()
print()
else:
print('\n')
print('This term doesn\'t exist.')
print()
print('----------------------------------------------------------------')
print()
print()
elif choice == 5:
print('\n')
print('The terms available are: ')
for term in terms:
print(term)
print()
print()
print('----------------------------------------------------------------')
print()
print()
else:
print('\n')
print('Sorry, but ', choice, ' is not a valid choice.\n')
print()
print('----------------------------------------------------------------')
print()
print()
答案 0 :(得分:3)
查看 pickle 模块,该模块提供了一种(de)将数据结构(在您的情况下为dict)序列化为可在需要时加载/转储的文件的方法。 p>