【问题标题】:How to categorize a list of data by keyword in python?如何在python中按关键字对数据列表进行分类?
【发布时间】:2020-11-03 03:03:29
【问题描述】:

我有一个交易清单,包括

*"AMZN mktp US*MH434G300", 
*"HEALTH CARE WEB PMT",* 
*"ARBYS #4323"** 

等,我想编写一个程序,在这些描述中查找关键字,并根据这些关键字分配一个类别。令人惊讶的是,我在互联网搜索中没有发现类似的东西,我想这可能是因为它很难做到。

到目前为止我所做的是这样的:

def getCategory(description):
    cat = ''
    if 'AMZN' in description:
       cat = 'shopping'
    elif 'ARBYS' in description:
        cat = 'restaurant'
return cat

虽然这确实有效,但非常辛苦,而且我必须为每个关键字编写单独的 if 语句。必须有更好的方法来做到这一点。 有这样的库吗?即使只是一种方法,我可以将一堆关键字添加到列表中,然后在 if 语句中使用该列表。

不担心速度/效率,因为没有大量的数据(几千个条目)。我正在使用python 3。我对任何学习经验都非常开放,我正在尝试更多地了解这类东西。任何建议都非常欢迎和赞赏。 谢谢!

【问题讨论】:

标签: python python-3.x dataframe data-science data-analysis


【解决方案1】:

虽然这仍然有点乏味,但它没有您的解决方案那么乏味。我会使用字典将每个关键字分配给特定的组。我会这样写:

def getCategory(description):
    my_dict = {'AMZN': 'shopping', 'ARBYS': 'restaurant'}
    for i in my_dict:
        if i in description:
            return my_dict[i]
    return None #Return none of none of the keywords are in the description

【讨论】:

  • 这是一个完美的临时解决方案。非常感谢!
【解决方案2】:

我必须为每个关键字编写一个单独的 if 语句。必须有更好的方法来做到这一点。

您可以使用dictionary 存储关键字到类别的映射,并迭代字典以找到匹配项。

categories_dict = {"AMZN": "shopping", "ARBYS": "restaurant"}

def get_category(description):
  for key in categories_dict:
    if key in description:
      return categories_dict.get(key)
  return None

【讨论】:

    【解决方案3】:

    使用链接的答案,这里有一些可能有用的示例代码:https://stackoverflow.com/a/33406474/13124888(参考)。

    在深入研究代码之前,我强烈建议您查看re(代表正则表达式),这是本机 Python 中的一个功能强大的库,可用于查找关键字、替换文本模式等。您可以在这里为这个库提供文档:https://docs.python.org/3/library/re.html

    另请参阅下面的代码 sn-p,它基于链接帖子中的代码:

    import re
    
    matches_list = ['AMZN', 'ARBYS', ... ]  # Keywords list
    matches_to_category = {'AMZN': 'shopping', 'ARBYS': 'restuarant', ...}  # keyword --> type dict 
    
    def match(input_string, string_list):
        cat = []  # Initialize
        words = re.findall(r'\w+', input_string)
        keywords = set([word for word in words if word in string_list])
        for keyword in keywords:  # Iterate over words found for a line
            cat.append(matches_to_category[keyword])  # Add category to keyword
        return cat
    
    >>> sentence = "AMZN is great for shopping; ARBYS has the meats!"
    >>> match(sentence, matches_list)
    ['shopping', 'restuarant']
    

    【讨论】:

      猜你喜欢
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 2022-06-17
      • 2015-01-23
      • 2012-05-24
      • 1970-01-01
      相关资源
      最近更新 更多