处理python应用程序中用户定义名称的拼写错误

2024-04-19 15:49:46 发布

您现在位置:Python中文网/ 问答频道 /正文

拼写错误的问题: 当您使用用户输入制作应用程序时,可能会出现不正确的输入。有拼写检查库可以处理它们,但是用户定义的数据可能不在字典中。例如,您正在构建一个聊天机器人,您需要输入位置名称来搜索餐厅。你知道吗


Tags: 数据用户名称应用程序字典定义机器人餐厅
1条回答
网友
1楼 · 发布于 2024-04-19 15:49:46

数据库层解决方案:

要处理这个问题,可以使用soundexapi。这些是作为小型库在所有技术中可用的标准api。它们在数据库SQL查询中也可用。你知道吗

以下是MySQL数据库的有效SQL查询之一: 从resturant中选择不同的r\u名称,其中area='South'和SOUNDEX(cost)=SOUNDEX('cheep')

在上面的示例中,数据库可能有“廉价”的条目,但用户输入了“cheep”。因此,上面的查询将返回cost='seap'的有效记录。你知道吗

python层中的解决方案:

Fuzzy库有Soundex和dmetaphoneapi。你知道吗

  1. 设置模糊的步骤:

    a.确保安装了python3并在路径中进行了设置 'C:\Program Files\Python36\Scripts'

    b.下载Fuzzy-1.2.2。焦油.gz来自https://pypi.python.org/pypi/Fuzzy的库

    c.将它们提取到一个文件夹中。你知道吗

    d.执行设置.py安装

  2. 在python中导入和测试:

    导入模糊

    dmtfn=fuzzy.d手机(四)

    打印(dmtfn('Hyderaabad'),dmtfn('Hyderabad'))

    >> [b'HTRP', None] [b'HTRP', None]
    

    打印(dmtfn('海德拉巴')[0],dmtfn('海德拉巴')[0])

    >> b'HTRP' b'HTRP'
    

真实用例(聊天机器人中的实体提取器):

当你为餐馆搜索构建聊天机器人时,你必须找到一个有效的位置,它被预定义为一个实体列表。因此,在将用户输入位置传递到数据库之前,应该将其识别为python层中的实体。在这种情况下,我们可以使用soundex ot dmetaphone。你知道吗

在代码段下面,从文件夹中读取实体(所有位置都可以在文件中)城市.txt)然后创建有效的实体列表。然后将实体列表转换为有效的DMetaphone代码。最后,将输入的位置转换为DMetaphone代码,并与先前创建的代码进行比较。你知道吗

    # read all entities from the entities folder
    # store them as dictionary, where key is filename
    files = os.listdir('./entities/')
    entities = {}
    for fil in files:
        lines = open('./entities/'+fil).readlines()
        for i, line in enumerate(lines):
            lines[i] = line[:-1]
        entities[fil[:-4]] = '|'.join(lines)

    # now convert the valid entities into codes
    if ' ' in uinput:
        codes = [dmtfn(w)[0] for w in uinput.lower().split()]
    else:
        codes = [dmtfn(uinput.lower())[0]]

    # If the code of input location matches with valid code list
    # then store the location as valid attribute for the intent
    for entity in entities:
        for i in entities[entity].split('|'):
            # entity extraction using sound code, to avoid spell mistakes
            # using soundex in database layer
            currCode = dmtfn(i.lower())[0]
            # print(currCode, i.lower())
            if currCode in codes:
                # if i.lower() in uinput.lower():
                attributes[entity] = i 

相关问题 更多 >