1

以下 Python 脚本:

def lookup(guildname):
    try:
        guildname = gw2api.get_guild_details(guildid)
        return guildname
    except:
        return''

返回如下所示的结果:(每个都是单行)

{u'emblem': {u'foreground_secondary_color_id': 443, u'foreground_primary_color_id': 584, u'foreground_id': 107, u'background_id': 27, u'flags': [], u'background_color_id': 11}, u'guild_id': u'4FAEB34C-BA01-49C8-AD19-C651D69F9981', u'tag': u'RAWK', u'guild_name': u'Ready And Willing Knights'}
{u'emblem': {u'foreground_secondary_color_id': 443, u'foreground_primary_color_id': 11, u'foreground_id': 144, u'background_id': 22, u'flags': [u'FlipBackgroundHorizontal'], u'background_color_id': 4}, u'guild_id': u'DDE74A26-FC28-4514-926D-9BB590E6BDD2', u'tag': u'AI', u'guild_name': u'Alchemy Incorporated'}
{u'emblem': {u'foreground_secondary_color_id': 64, u'foreground_primary_color_id': 146, u'foreground_id': 148, u'background_id': 21, u'flags': [], u'background_color_id': 617}, u'guild_id': u'190E573E-8970-440E-8EA1-653098296EDB', u'tag': u'RoMS', u'guild_name': u'Roses Of The Moonlight Sigil'}

使用正则表达式我想我可以获得公会名称

([A-Z0-9a-z-]*\b [A-Z0-9a-z-]*)

但是我如何将它应用到上面的 python 脚本中呢?它只需要返回唯一的公会名称Roses Of The Moonlight SigilAlchemy Incorporated而不是那个巨大的大块。不太确定我的表达是否正确

使用适当的功能进行编辑:

import json, gw2api

getguild = gw2api.get_servers()
guildapi = json.dumps(getguild)
apiresult = json.loads(guildapi)

print apiresult['name']
4

2 回答 2

3

使用json.loads(),然后将其作为普通字典访问。不需要正则表达式:

import json
...
return json.loads(guildname)

thedict = the_one_returned
print thedict['guild_name']
# Prints Ready And Willing Knights
于 2013-07-06T10:18:36.427 回答
2

您可以使用ast.literal_eval,它会安全地将这些字符串转换为 dict 对象,然后您可以从该 dict 中获取任何键:

演示:

>>> from ast import literal_eval
>>> strs = "{u'emblem': {u'foreground_secondary_color_id': 443, u'foreground_primary_color_id': 584, u'foreground_id': 107, u'background_id': 27, u'flags': [], u'background_color_id': 11}, u'guild_id': u'4FAEB34C-BA01-49C8-AD19-C651D69F9981', u'tag': u'RAWK', u'guild_name': u'Ready And Willing Knights'}"
>>> dic = literal_eval(strs)
>>> dic[u'guild_name']
u'Ready And Willing Knights'
于 2013-07-06T10:20:22.247 回答