添加行时如何让我的字典discord.py bot停止循环

时间:2021-05-31 11:25:23

标签: python dictionary discord nltk wordnet

所以我在互联网上找到了这个开源 discord.py bot,它使用 wordnet 来获取任何给定单词的定义。它应该首先发送单词所在的词性(名词,动词,形容词),然后在其下方,应该有单词的多个定义。

然而,当前代码在整个过程中不断循环。添加单词的每个新定义时,它会不断重复词性部分。您可以在下图中亲眼看到我的意思:

What it looks like now

如您所见,这会导致不必要的长消息。相反,我希望它是否事先添加了所有积分并仅发送成品。像这样:

名词

  1. ...
  2. ...
  3. ...
  4. ...
  5. ...
  6. ...

这是当前代码:

nltk.download("wordnet")
from collections import defaultdict
from nltk.corpus import wordnet

def format_meaning(word, synsets, m):
  person = str(m.author.mention)
  log = person + ", the definition is:\n\n"
  reply = f"**{word}**\n\n"
  char = 0

  # Group by POS
  grouped = defaultdict(list)

  for synset in synsets:
    grouped[PARTS_OF_SPEECH[synset.pos()]].append(synset.definition())

    for pos, definitions in grouped.items():
      if char > 1250:
        return log + reply
      reply += f"*{pos}*\n"
      char += len(f"*{pos}*\n")
      for counter, definition in enumerate(definitions, 1):
        reply += f"    {counter}. {definition}\n"
        char += len(f"    {counter}. {definition}\n")
        
  return log + reply

我有一些使用 Python 的经验,但这有点超出我的想象,我对如何让它工作感到茫然。所以,任何帮助将不胜感激!

0 个答案:

没有答案