如何实现Python Bot自动校正?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (95)

是否可以添加一个选项来自动更正BOT回复中的单词。例如:在下面的代码中,当我们使用?ping时会反馈:hello i'm in USA now going to UK tomorrow,但是应该自动纠正Autocorrect_List,应该回答:hello i'm in United States Of America now going to United KingDom tomorrow

Autocorrect_List = [USA = United States Of America, UK = United KingDom]

@bot.command(pass_context=True)
async def ping(ctx):
    msg = "hello i'm in USA now going to UK tomorrow".format(ctx.message)
    await bot.say(msg)
提问于
用户回答回答于

只需要一个循环和大量的替换就能实现,自动更正的“list”应该是dict,因为dict是Python的映射类型

autocorrect = {'USA': 'United States Of America', 'UK': 'United Kingdom'} 

msg = "hello i'm in USA now going to UK tomorrow"
for k, v in autocorrect.items():
    msg = msg.replace(k, v)

print(msg)
# hello i'm in United States Of America now going to United Kingdom tomorrow

应该考虑保存消息的基本格式(与已替换的消息一起),这样可以提高效率,而不是在重复使用时生成所有内容。

考虑使用SkilledFire的解决方案,或者如果你使用python 3.6+,可以使用f-字符串格式:

d = {'USA': 'United States Of America', 'UK': 'United Kingdom'} 

msg = f"hello i'm in {d['USA']} now going to {d['UK']} tomorrow"

print(msg)
# hello i'm in United States Of America now going to United Kingdom tomorrow

最好的方法仍然是在信息被替换后保存。

用户回答回答于

以下方法更好:

autocorrect = {'USA': 'United States Of America', 'UK': 'United KingDom'}
@bot.command(pass_context=True)
async def ping(ctx): 
   msg = "{}, {}    etc...".format(autocorrect['USA'], autocorrect['UK'],ctx.message)
   await bot.say(msg)

扫码关注云+社区

领取腾讯云代金券