【问题标题】:operate over values of a dictionary when values are lists当值是列表时对字典的值进行操作
【发布时间】:2023-01-30 20:48:14
【问题描述】:

假设我有以下字典:

data = {'ACCOUNT_CLOSURE': ['account closure',
  'close account',
  'close bank',
  'terminate account',
  'account deletion',
  'cancel account',
  'account cancellation'],
 'ACCOUNT_CHANGE': ['change my account',
  'switch my account',
  'change from private into savings',
  'convert into family package',
  'change title of the account',
  'make title account to family',
  'help me access the documentation']}

我想遍历每个键,然后遍历值的元素并删除停用词,所以我这样做:

stop_words = set(stopwords.words("english"))

for key, values in data.items():
    data[key] = [value for value in values if value not in stop_words]

但这会返回与我原来的字典完全相同的字典。我想知道我做错了什么?

【问题讨论】:

    标签: python dictionary nltk


    【解决方案1】:

    您正在使用 nltk 库中的停用词集,它只包含单词而不包含短语。您需要过滤每个值短语中的单词而不是整个值。试试这个代码:

    for key, values in data.items():
    data[key] = [
    " ".join([word for word in value.split() if word not in stop_words])
    for value in values
    ]
    

    【讨论】:

    • 这返回字符列表并且不正确
    • 你怎么知道的停用词nltk
    • @Pingu 我正在使用 NLTK 停用词,即 stopwords.words("english") 并且是我的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2015-10-18
    • 2010-11-15
    • 2013-04-04
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多