gpt4 book ai didi

python - 在 json 文件中搜索字符串

转载 作者:行者123 更新时间:2023-12-01 03:54:57 25 4
gpt4 key购买 nike

我有一个字典,用户在开始时输入值,然后这些值以 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

最佳答案

import json
import sys
import os
data = []
if os.stat("data.txt").st_size != 0 :
file = open('data.txt', 'r')
data = json.load(file)
print(data)

choice = input("What's your choice ?")
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 punchline 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 sub_dict in data:
if searchTerm in sub_dict['setup']:
print(sub_dict['punchline'])
pass
# or you could modify the last for loop, like this:
for dict in data:
if searchTerm in dict['setup'] or searchTerm in dict['punchline']:
print('found!')
pass

关于python - 在 json 文件中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com