【发布时间】:2016-06-05 13:19:13
【问题描述】:
我有一个字典,用户在开始时输入值,然后将这些值以 json 格式存储到 txt 文件中。目标是让用户能够使用他们选择的字符串搜索 json 文件。我尝试了多种方法,但都没有成功。下面的代码显示如果用户输入“s”,那么他们将被提示输入搜索词。然后代码加载 json 文件并将文件中的信息存储到一个名为“data”的“列表”中,然后代码尝试搜索列表中的每个项目并将其与用户输入的 searchTerm 进行比较
将用户输入放入 txt 文件(json 格式)的代码
if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
jokeSetup = input('Enter setup of joke: ')
jokePunchLine = input('Enter puncline of joke: ')
entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
data.append(entry)
file = open('data.txt', 'w')
json.dump(data, file)
file.close()
print('Joke Added.')
pass
elif choice == 's':
# Search the current jokes.
# See Point 5 of the "Requirements of admin.py" section of the assignment brief.
searchTerm = input('Enter search term: ')
file = open('data.txt', 'r')
data = json.load(file)
file.close()
for item in data:
if searchTerm in data:
print ('found it')
pass
【问题讨论】:
-
你的数据格式是什么?你能给我们举个例子吗?
-
@quemeraisc 这是我加载到 json 文件条目中的字典的格式 = {'setup': jokeSetup , 'punchline': jackPunchLine}
-
您应该在完成搜索后关闭该文件
标签: python json list dictionary