【问题标题】:How to parse data from file Json or Excel如何从文件 Json 或 Excel 中解析数据
【发布时间】:2018-07-14 11:20:37
【问题描述】:

我得到了一个从 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)

当我们在不和谐频道中键入 ?mention @user 时,机器人会提供该用户数据。但我还需要 2 个帮助。

  1. bot 需要从多个 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

【问题讨论】:

  • 其他 json 文件中有什么?您应该在启动机器人时加载所有这些信息(将代码放在on_ready 事件中)。然后在调用命令时循环遍历 Python 对象。
  • 我可以得到一个示例代码如何做到这一点?我也试图让用户输入的名称工作,而不是用用户 ID 标记用户。
  • Python 逐行读取它们,因此文件大小并不重要。 2000 个 json 条目并没有那么大。这将允许您对单个文件名进行硬编码。如果您有多个名为 George 的用户,您希望发生什么?

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


【解决方案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))

【讨论】:

  • for record on d 中出现语法错误,无法运行机器人。
  • 错字,是for record in d
  • 然后你可以遍历所有文件并将它们加载到字典中
  • 知道如何解决这个问题。我需要同时使用这个 json 命令和小写大写命令。
  • index[record['Name']].append(record)。让它index[record['Name'].lower()].append(record)。您也可以对另一个 append 进行操作,但我认为其中不可能包含字母。
猜你喜欢
  • 2019-06-03
  • 1970-01-01
  • 2017-02-03
  • 2018-04-07
  • 2023-03-27
  • 2021-05-29
  • 2012-05-16
  • 1970-01-01
相关资源
最近更新 更多