【问题标题】:Applying function to a specific subkey for each key using a dictionary comprehension使用字典理解将函数应用于每个键的特定子键
【发布时间】:2018-10-21 23:18:25
【问题描述】:

我正在尝试执行仅将函数应用于特定内部子键的字典理解。该函数从字符串中删除非英语单词。对于字典中的每个键,我希望它应用于'title' 子键。

# imports

import nltk

# function to remove non-English words

words = set(nltk.corpus.brown.words())

def strip_non_en(string, words):
    " ".join(w for w in nltk.wordpunct_tokenize(string)\
    if w.lower() in words or not w.isalpha())
    return string


# dict example:

meta_data = {
'12345.xml': {'author': ['Presley'],
'date': 1956,
'doi': None,
'title': 'Heartbreak Hotel'},
'67890.xml': {'author': ['Iglesias'],
'date': 1972,
'doi': None,
'title': 'For a little bit of your love Por Un Poco De Tu Amor'}
}

我只能让它将功能应用于所有子键,这往往会删除'author'子键的内容。

感谢所有帮助。

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:

    这是构建逻辑的一种方式。类似于 Ajax1234,但我在strip_non_en 中添加了一个额外的可选参数。

    word_set = set(nltk.corpus.brown.words())
    
    def strip_non_en(string, words=word_set, key=None):
        if key in (None, 'title'):
            string = ' '.join(w for w in nltk.wordpunct_tokenize(string) \
                              if w.lower() in words or not w.isalpha())
        return string    
    
    new_dict = {a: strip_non_en(b, key=a) for a, b in meta_data.items()} 
    

    【讨论】:

      【解决方案2】:

      可以检查当前key是否为'title',如果是,则调用函数并将当前值传递给函数:

      new_dict = {a:strip_non_en(b, words) if a == 'title' else b for a, b in meta_data.items()} 
      

      此外,您可以稍微更改函数strip_non_en,以便参数words 是可选的。这样,words 就不必每次都传递:

      def strip_non_en(string, words=words):
        " ".join(w for w in nltk.wordpunct_tokenize(string)\
        if w.lower() in words or not w.isalpha())
        return string
      
      new_dict = {a:strip_non_en(b) if a == 'title' else b for a, b in meta_data.items()} 
      

      【讨论】:

        猜你喜欢
        • 2020-06-19
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多