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]
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)
请尝试以下操作:
这是因为^{} 可以接受前缀元组作为参数。
注意,我将
string
重命名为sentence
,因此字符串模块没有任何歧义。这是一个可能的解决办法。我使用的是
regex
,因为这样可以轻松地去掉标点符号。另外,我正在使用collections.Counter
如果字符串有很多重复的单词,这可能会提高效率。最后一部分可以通过列表理解来完成:
结果:
试试这个:
上面将返回一个列表,其中包含字符串中与标记列表中的前缀匹配的所有单词。
相关问题 更多 >
编程相关推荐