我怎么能找到这个词是Substitutions:或者Insertions

2024-10-02 08:17:45 发布

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

例如,我的词是“大脑”,我们需要创建一个函数来检查它是不是替代和插入。 例如,替代品可以是:训练粒痘。。。插入:barain bryain

#I am not sure I did the right way or missing something. And any other way that faster?
#string0 is pattern

def subsitutions(string0, string1):
     sublist = []
    for i in range(len(string0)):
        sublist.append(string0[:i] + string0[i + 1:])
    for i in range(len(string1)):
        if string1[:i] + string1[i + 1:] in sublist:
            print("This word is subsitutions")
            break

def insertions(string0, string1):
    if len(string0)+1 == len(string1):
        for i in range(len(string1)):
            if string1[:i] + string1[i + 1:] == string0:
                print("This word is insertions")
                break

Tags: inforlenifisdefrangethis
2条回答

看看这是否有用

word = "brain"
word_length = len(word)

words_to_check = ["train", "grain", "blain", "bryin", "barain", "bryain"]

for word_to_check in words_to_check:
    boolean_list = [character in word for character in word_to_check]
    character_occurences = sum(boolean_list)
    if character_occurences == word_length - 1:
        print("{0} is substitution".format(word_to_check))
    elif character_occurences >= word_length - 1 and len(boolean_list) > word_length:
        print("{0} is insertion".format(word_to_check))

set.difference很容易为您做到这一点:

>>> set('brian') - set('bryan')
{'i'}
>>> set('brian') - set('byrian')
set()

下面是这张支票的一个肮脏的例子:

def check_sub_or_ins(pattern, string):
    if set(pattern) - set(string):
        print("This word is subsitutions")
    else:
        print("This word is insertions")

您需要检查每个字符串的长度,因为仅仅使用set并不能适用于所有字符串

相关问题 更多 >

    热门问题