如何使用仅向前遍历的Python从字符串中获取可能的单词

2024-09-28 05:17:13 发布

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

from collections import Counter


def possiblewords(input, charset):
    # traverse words in list one by one
    for word in input:
        # convert word into dictionary
        dict = Counter(word)
        # now check all keys of corrent word are present in given character set
        flag = 1
        for key in  dict.keys():
            if key not in charset:
                flag = 0
        # if all keys are present (flag = 1) then print the word
        if flag == 1:
            print(word)

# Driver program


if __name__ == "__main__":
    input = [ 'nipple','apple','pine','pile']
    str = "pineapple"
    charset = list(str)
    possiblewords(input, charset)

上面的程序输出“pin,apple,pine,pile,nipple”

我想改变程序,它将给出结果,通过向前遍历字母只。这意味着当我使用str=“菠萝”时,我只想要结果“松树,苹果”。但是这个程序用“菠萝”这个词的字母给出了其他可能的词。我知道,通过删除的话乳头,并桩这将是好的。但我必须给所有的词下定义。如何解决这个问题


Tags: inforinputifcounterkeysallone
2条回答

可以使用python的find方法

def possiblewords(input, charset):
    for word in input:
        if charset.find(word) != -1:
            print(word)

if __name__ == "__main__":
    input = [ 'nipple','apple','pine','pile']
    str = "pineapple"
    # Do not convert string to list
    possiblewords(input, str)

将代码重写为

from collections import Counter

def possiblewords(input, charset):
    # traverse words in list one by one
    for word in input:
        if str.find(word) != -1:
            print (word)

# Driver program
if __name__ == "__main__":
    input = [ 'nipple','apple','pine','pile']
    str = "pineapple"
    possiblewords(input, str)

相关问题 更多 >

    热门问题