python:按照我自己的规则对字符串进行分类和分组

时间:2018-06-13 17:16:09

标签: python regex string design-patterns categorization

我正在寻找将字符串列表分类为我指定的组的方法。如果我有以下内容,

keywords = ['cat', 'dog']
number = '0123456789'

并输入'cat 30495 hello'我想要这个属于类似的组:[keywords] [number] [不是关键字的字符串]。什么是解决此类问题的有效方法?谢谢。

1 个答案:

答案 0 :(得分:0)

按照您的示例,可以编写如下函数。 不确定你期望不同的规则。

def categorizer(input_text):
    # this will be our result list
    categories = []

    # Rule number 1 - list of keywords
    keywords = ['cat', 'dog']
    #Rule number 2 - if it is number

    # find the components in the input
    # make them lowercase and strip additional white space
    elements = [i.lower().strip() for i in input_text.split(' ')]

    for ele in elements:
        if ele in keywords:
            categories.append('keyword')
        elif ele.isdigit():
            categories.append('number')
        else:
            categories.append('none')
    return categories

print categorizer('cat 30495 hello')

输出是 ['关键字','数字','无']