我如何搜索关键字并打印它周围的所有内容,但仍然在{}括号之间 - python

时间:2018-03-16 23:53:19

标签: python split format edit cut

我有字符串

{"quests ":
    [{
         "title ":"Phite Club",
         "status": "COMPLETED",
         "difficulty": 3,
         "members": True,
         "questPoints": 1,
         "userEligible": True
    },{
         "title": "All Fired Up",
         "status": "COMPLETED",
         "difficulty": 1,
         "members": True,
         "questPoints": 1,
         "userEligible": True
    }]
}

我想搜索All Fired Up并输出为:

{"title": "All Fired Up", 
 "status": "COMPLETED",
 "difficulty": 1,
 "members": True,
 "questPoints": 1,
 "userEligible": True}

我不一定需要输出中的引号或{},但我需要数据。

我的格式很差,但感谢任何帮助,谢谢!

3 个答案:

答案 0 :(得分:1)

回答修订后的问题

让我们定义你的词典:

>>> d = {"quests ":
...     [{
...          "title ":"Phite Club",
...          "status": "COMPLETED",
...          "difficulty": 3,
...          "members": True,
...          "questPoints": 1,
...          "userEligible": True
...     },{
...          "title": "All Fired Up",
...          "status": "COMPLETED",
...          "difficulty": 1,
...          "members": True,
...          "questPoints": 1,
...          "userEligible": True
...     }]
... }

要检索您感兴趣的部分:

>>> [y for dd in d.values() for y in dd if y.get('title') == 'All Fired Up']
[{'questPoints': 1, 'title': 'All Fired Up', 'status': 'COMPLETED', 'userEligible': True, 'members': True, 'difficulty': 1}]

或者,如果您提前知道您要找的是quests

>>> [y for y in d['quests '] if y.get('title') == 'All Fired Up']
[{'questPoints': 1, 'title': 'All Fired Up', 'status': 'COMPLETED', 'userEligible': True, 'members': True, 'difficulty': 1}]

回答问题的原始版本

让我们定义你的字符串:

>>> s = '"{"quests":[{"title":"Phite Club","status":"COMPLETED","difficulty":3,"members":true,"questPoints":1,"userEligible":true},{"title":"All Fired Up","status":"COMPLETED","difficulty":1,"members":true,"questPoints":1,"userEligible":true},"'

让我们提取您想要的部分:

>>> import re
>>> re.findall(r'\{[^}]*All Fired Up[^}]*\}', s)
['{"title":"All Fired Up","status":"COMPLETED","difficulty":1,"members":true,"questPoints":1,"userEligible":true}']

正则表达式\{[^}]*All Fired Up[^}]*\}匹配All Fired Up及其周围的所有字符,包括前面最近的{和后面的}

[请注意,在当前版本的问题中,字典的密钥questsquests之后有一个空格。上面的代码

JSON问题

在我写这个答案时,问题中的字符串是不是有效的JSON。如果在以后的更新中,用有效的JSON字符串替换,则Daniel Roseman's answer变得合适。

答案 1 :(得分:0)

string = ".... your string ..."
data = [ s.split("}")[0] for s in string.split("{") if "All Fired Up" in s ]

答案 2 :(得分:-1)

你有一个JSON字符串。您应该将其解析为python,然后搜索您的匹配。

data = json.loads(mystring)
target = next(item for item in data if item["title"] == "All Fired Up")