【问题标题】:search for string in json file在 json 文件中搜索字符串
【发布时间】: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


【解决方案1】:
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

【讨论】:

  • 或类似的东西,根据您对数据中 sub_dict 的要求: if searchTerm in sub_dict['setup'] or searchTerm in sub_dict['punchline']: print('found!')
【解决方案2】:

你可以这样做:

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 item in data[0].items():
        if searchTerm in str(item[1]):
            print ('found it')

    pass

# or the for loop could be like this
for sub_dict in data:
    if searchTerm in sub_dict['setup'] or searchTerm in sub_dict['punchline']:
        print('found!')

【讨论】:

  • AttributeError: 'list' 对象没有属性 'items'
  • 你的数据格式是什么?考虑到那个 json 示例,上面的代码对我有用。
  • entry = {'setup': jokeSetup , 'punchline': jackPunchLine} 这是我转储到 json 文件 @Jomy Emmanuel 的字典
  • 我在帖子中添加了更多代码,以展示我如何让用户输入到 txt 文件(json 格式)
  • 我已经编辑了我的答案。您可以直接执行 json.dump(entry, file),而不是将条目附加到数据。在这种情况下,不需要 data[0].items(),而 data.items() 应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 2012-01-03
  • 2011-01-12
  • 2011-01-31
  • 2021-10-20
  • 2011-06-26
相关资源
最近更新 更多