将字符串与Python中的片段列表进行比较

时间:2012-12-03 21:54:24

标签: python string

我有一长串职位描述标题,我需要根据它们对组织的重要性进行筛选。我已经开发了一个简单的启发式方法。例如,如果标题包含“管理员”或“导演”之类的单词,则很重要。如果没有这个测试,如果它包含“副”或“助手”这样的词,那么它就不重要了。

这很容易用Python中的几行来完成,但我想知道是否有更多的Pythonic方法来实现它。这就是我现在的位置。

def in_fragment(phrase, fragments):
    for fragment in fragments:
        if fragment in phrase:
            return True
    return False

完美无缺,但如果可能的话,会以正确的方式爱它!感谢。

3 个答案:

答案 0 :(得分:4)

一种方法是使用any

def in_fragment(phrase, fragments):
    return any(x in phrase for x in fragments)

答案 1 :(得分:2)

嗯......可能F.C.的answer比我要编写的更清晰,但是自从我用sets在我的计算机上测试它之后,就在这里:

#!/usr/bin/env python

a="this is a letter for the administrator of the company"
important = set(["administrator", "director"])

hits=important.intersection(set(a.split(" ")))
if len(hits) > 0:
    print "Wo! This is important. Found: %s" % (hits)

也许你会觉得它有用......对于某些事情...... :)

答案 2 :(得分:0)

def rankImportance(titles, fragments):
    """titles is a list of job titles
       fragments is a list of sets. 
         At index 0: set(['administrator', 'director'])
         At index 1: set(['deputy', 'assistant'])
         etc..."""

    answer = collections.defaultdict(list)
    while titles:
        done = set()
        for i,title in enumerate(titles):
            for r,words in enumerate(fragments):
                if any(word in title for word in words):
                    answer[r].append(title)
                    delete.add(i)
        titles = [title for i,title in enumerate(titles) if i not in delete]

    return answer

这应该返回一个字典,其中的键是作为职位列表的等级和值的键。等级值越小,越重要。最小等级为0。

希望这有帮助