In [1]:
dictionary = {
    "北京烤鸭",
    "特别",
    "喜欢"
}
sentence = "他特别喜欢北京烤鸭"
In [2]:
def seg(sentence):
    res = []
    def maxmatch(res, sentence, dictionary):
        if len(sentence) == 0:
            return list()
        for i in reversed(range(1, len(sentence)+1)):
            fw = sentence[:i]
            rw = sentence[i:]
            if fw in dictionary:
                res.append(fw)
                return maxmatch(res, rw, dictionary)
        res.append(fw)
        return maxmatch(res, rw, dictionary)
    maxmatch(res, sentence, dictionary)
    return res
In [3]:
seg(sentence)
Out[3]:
['他', '特别', '喜欢', '北京烤鸭']
In [ ]: