python - 解压过滤器对象
问题描述
我正在学习 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']]]
谁能帮我解决这个问题?对此,我真的非常感激!
解决方案
我认为您需要更改此行;
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]
推荐阅读
- selenium - (IDE)单击选项说确定但什么也不做
- python - 在 sklearn 中使用 make_regression 函数的问题
- python - Pandas 将 json 转换为单个单元格 csv 而不是完整的电子表格
- c# - 加速 C# 原生调用 pinvoke
- r - 将数据帧转换为r中的二进制特征
- react-native - 将 noHoist 添加到项目后,React Native 无法解析本地模块
- html - 所有网格功能在 cPanel HTML 编辑器中显示为未知属性
- ios - 如何使用 IBOutlet 更新 UIView 的恒定高度约束
- google-sheets - 使用上限分配值
- c++ - 如何检查集合的元素在 C++ 中是否等于零?