如何解析文件Json或Excel中的数据

时间:2018-07-14 11:20:37

标签: json python-3.x discord.py

我有一个代码可以解析json文件中的数据,但仍然不完整。

{"people": [
{"UserID": "xxxxx123", "Name": "Steve", "Sex": "Male", "age": "30"},
{"UserID": "xxxxx124", "Name": "Rachel", "Sex": "Female", "age": "25"},
{"UserID": "xxxxx125", "Name": "George", "Sex": "Male", "age": "22"} ] }

@bot.command(pass_context=True)
async def mention(ctx, member: discord.Member):
  with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
      if(p['UserID'] == str(member.id)):
        await bot.send_message(ctx.message.channel, p)

当我们在Discord Channel bot中输入?mention @user时,将提供该用户数据。但是我还需要2个帮助。

  1. 机器人需要从多个json文件或excel表格1 2 3等中获取数据。
  2. 获取用户数据应该是?mention xxxxx123?mention George,而不是标记用户。

在服务器中运行时更新错误:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/home/bosen/.local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "bot.py", line 37, in on_ready
    d = json.load(f)
  File "/home/bosen/.local/lib/python3.6/json/__init__.py", line 296, in load
    return loads(fp.read(),
  File "/home/bosen/.local/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

1 个答案:

答案 0 :(得分:1)

我会将json中的列表重新索引为具有两个索引的字典:将名称和ID都映射到记录列表。

import json
from collections import defaultdict

index = defaultdict(list)

@bot.event
async def on_ready():
    global index
    for filename in ('data1.json', 'data2.json'):
        with open(filename) as f:
            d = json.load(f)
            for record in d['people']:
                index[record['UserId'].lower()].append(record)
                index[record['Name'].lower()].append(record)

@bot.command(pass_context=True)
async def mention(ctx, *keys):
    for key in keys:
        for record in index[key]:
            await bot.say("{Name} is a {age} year old {Sex}  with id {UserId}".format(**record))