python - 在Python中根据声音/同音词匹配字符串?

标签 python matching

我正在开发一个Python程序,该程序一步接受输入(字符串),并将其与用户库中的歌曲/艺术​​家进行匹配。然而,我在弄清楚输入/库包含数字/特殊字符时如何匹配时遇到了一些困难。以“All-4-One”小组为例。在我的图书馆中,它可能会完全像这样列出。我需要将其与以下任何输入相匹配:

  • 全四合一(当然)
  • 全部 4 个一(无破折号)
  • 全 4 1(全数字)
  • 全部四一(全部拼写出来)
  • all for one(“四”的拼音)

或者,实际上,任何其他听起来相同的组合。这样做的原因是输入来自语音识别系统,因此用户说出“4”可以被识别为“for”、“four”或“4”。我想象 Alexa/Siri/Google 都会做这样的事情(因为你可以要求他们播放歌曲/艺术​​家),但我想用 Python 实现这一点。我怎样才能做到这一点?

最佳答案

对于每个名称,首先规范化字符串:删除“-”、“”或“\”等符号,替换您想要的音标。

all-4-1 becomes ["all", "for" ,"one"]
all-four-1 becomes ["all", "for" ,"one"]
crappy\"new"\1 becomes ["crappy", "nju", "one"]

然后匹配完整列表,或者只匹配一些单词,例如出现“for”,“one”表示存在该组的可能性为66%。

替代创建一个字典,例如: dict { "4":"for", "four": for", 1:"one", new:"nju"} 等等... 或创建一个文件,例如: 子.txt: 4 为 四个为 1 一 ... 并读入字典。 当你创建这个时,你可以将它链接到我,因为我也有一个项目,我可能需要音标替换:D

我很匆忙地创建了非常阿尔法版本(进一步修改了一点):

    '''
Created on Jan 29, 2018

@author: noob
'''
import re

path = "X:/Programming/workspaceEclipse/PyTutorials/"

sounds = open(path + "txt/sounds.txt", 'r')


def toDict(file):
    dict = {}
    for line in file:
        key, val = line.strip().split(" ")
        dict[key] = val
    return dict


d = toDict(sounds)

print("dict:" , d)

str1 = r"be4-the-storm"
str2 = r"u2/best/hits"
str3 = r"A.B.B.A- what4"
str4 = r"all-4-one"
str5 = r"all four one"
str6 = r"all 4 1"
str7 = r"w8-4ever"

strs = [str1,str2,str3,str4,str5,str6,str7]



def toNorma(words,dict):
    ret= []
    for word in words:
        w = word.lower()
        ret.append(dict.get(w ,w ))
    return ret    

def toNormaStr(str):
    return toNorma(re.findall(r'w8|m8|[0-9]|[a-zA-Z]+', str), d)
#exceptions like w8,m8 come first in the regex

def show(str):
    print(str + ":" ,toNormaStr(str) )

for str in strs:
    show(str)

哪里 sound.txt 是:

    a ei
b bi
c si
d di
f ef
g gi
h ejch
i aj
j dzhej
k kej
l el
m em
n en
o ou
p pi
q kju
r a
s es
t ti
u ju
v vi
w dabelju
x eks
y waj
z zet
1 wan
2 to
3 thri
4 for
5 faiw
6 siks
7 seven
8 ejt
8 ajt
9 najn
10 ten
one wan
two to
three thri
four for
five faiw
six siks
eight ejt
nine najn
w8 vejt
m8 majt
what vot

输出如下:

     be4-the-storm: ['be', 'for', 'the', 'storm']
u2/best/hits: ['ju', 'to', 'best', 'hits']
A.B.B.A- what4: ['ei', 'bi', 'bi', 'ei', 'vot', 'for']
all-4-one: ['all', 'for', 'wan']
all four one: ['all', 'for', 'wan']
all 4 1: ['all', 'for', 'wan']
w8-4ever: ['vejt', 'for', 'ever']

关于python - 在Python中根据声音/同音词匹配字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48508873/

相关文章:

python - Django 1.6 中的 ATOMIC_REQUEST 和事务

python - 在 python 函数中使用列表

r - 在 R 中使用 'fastmatch' 包

c# - 从占位符获取字符串值 C#

python - 用 matplotlib 表示体素

python - 文件扩展名命名 : . p vs .pkl vs .pickle

R:基于多个变量/列/约束查找相似/"duplicate"条目对

linux - 执行sed命令时出错

c++ - C++ 中多个帧的 Blob ID 匹配(图像分析)

python - python 如何计算 "is"表达式?