首页 > 解决方案 > 解压过滤器对象

问题描述

我正在学习 NLP 课程并试图理解书中提供的代码。我试图在 Jupyter 中使用 Python 3 运行它,并得到了意外的结果,即对象列表,而不是书中过滤的令牌列表。我知道作者使用的是 Python 2,所以这可能是原因,并且必须有一些方法可以使代码在 Python 3 中工作。我尝试使用 list() 打印它,但它仍然给出相同的结果。以下是代码:

def remove_characters_after_tokenization(tokens):
        pattern = re.compile('[{}]'.format(re.escape(string.punctuation)))
        filtered_tokens = filter(None, [pattern.sub('', token) for token in tokens]) 
        return filtered_tokens 

       filtered_list_1 =  [filter(None,[remove_characters_after_tokenization(tokens) for tokens 
       in sentence_tokens]) for sentence_tokens in token_list]
       print(filtered_list_1)

       [<filter object at 0x7fb28c08fb20>, <filter object at 0x7fb28c08faf0>, <filter object at 
       0x7fb28c303910>]

这是预期的令牌列表:

[[['The', 'brown', 'fox', 'was', 'nt', 'that', 'quick', 'and', 'he',
     'could', 'nt', 'win', 'the', 'race']], [['Hey', 'that', 's', 'a', 'great',
     'deal'], ['I', 'just', 'bought', 'a', 'phone', 'for', '199']], [['You',
     'll', 'learn', 'a', 'lot', 'in', 'the', 'book'], ['Python', 'is', 'an',
     'amazing', 'language']]]

谁能帮我解决这个问题?对此,我真的非常感激!

标签: pythonnlp

解决方案


我认为您需要更改此行;

filtered_list_1 =  [filter(None,[remove_characters_after_tokenization(tokens) for tokens 
   in sentence_tokens]) for sentence_tokens in token_list]

至:

filtered_list_1 =  [list(filter(None,[remove_characters_after_tokenization(tokens) for tokens 
   in sentence_tokens])) for sentence_tokens in token_list]

推荐阅读