python中的前缀匹配

2024-06-06 23:06:21 发布

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

我有一根绳子像:

" This is such an nice artwork"

我有一个标签列表["art","paint"]

基本上,我想编写一个函数,它接受这个字符串和标记列表作为输入 并返回“artwork”一词,因为artwork包含标记列表中的art一词。

我怎样才能最有效地做到这一点?

我希望在速度上有效率

 def prefix_match(string, taglist):
        # do something here
     return word_in string

Tags: 函数字符串标记an列表stringis标签
3条回答

请尝试以下操作:

def prefix_match(sentence, taglist):
    taglist = tuple(taglist)
    for word in sentence.split():
        if word.startswith(taglist):
            return word

这是因为^{}可以接受前缀元组作为参数。

注意,我将string重命名为sentence,因此字符串模块没有任何歧义。

这是一个可能的解决办法。我使用的是regex,因为这样可以轻松地去掉标点符号。另外,我正在使用collections.Counter如果字符串有很多重复的单词,这可能会提高效率。

tag_list =  ["art","paint"]

s = "This is such an nice artwork, very nice artwork. This is the best painting I've ever seen"

from collections import Counter
import re

words = re.findall(r'(\w+)', s)

dicto = Counter(words)

def found(s, tag):
    return s.startswith(tag)

words_found = []

for tag in tag_list:
    for k,v in dicto.iteritems():
        if found(k, tag):
            words_found.append((k,v))

最后一部分可以通过列表理解来完成:

words_found = [[(k,v) for k,v in dicto.iteritems() if found(k,tag)] for tag in tag_list]

结果:

>>> words_found
[('artwork', 2), ('painting', 1)]

试试这个:

def prefix_match(s, taglist):
    words = s.split()
    return [w for t in taglist for w in words if w.startswith(t)]

s = "This is such an nice artwork"
taglist = ["art", "paint"]
prefix_match(s, taglist)

上面将返回一个列表,其中包含字符串中与标记列表中的前缀匹配的所有单词。

相关问题 更多 >