首页 > 解决方案 > 从字符串列表中提取标记集

问题描述

我有一个字符串列表,我想将所有标记提取到一组标记中 - 而不是一组列表。我需要混合所有令牌。

我的句子存储为“句子”中的字符串列表

所以如果尝试:

words = set([])
a=set(sentences[1].split())
b=set(sentences[2].split())
a.union(b)

我在这样的一组中得到 a 和 b 组。这就是我正在寻找的

{',', '.', '2.252', '35-1/7', '37-year-old', 'B', 'Blood', 'Fred', 'G4', 'Grauman', 'O+', 'P3-5', 'pregnancy', 'product', 'rubella', surface', 'the', 'to', 'type', 'week', 'woman'}

但是通过列表理解

words = set()
[words.union(set(sent.split())) for sent in sentences]

输出是一个集合列表,像这样

[{'.',  'Care',  'He',  'Intensive',  'Neonatal''}, {'.',  '2.252',  35-1/7',  '37-year-old',  'Fred',  'G4',  'Grauman','}]

有没有像列表理解这样的紧凑代码行来获得我需要的东西?

====

好吧,我刚刚做了,在对“单词”进行列表理解之后,

a = set()
a.union(*words)

标签: pythonlistset

解决方案


如果您的句子是字符串,您可以将它们加入并再次拆分。

set(" ".join(sentences).split())

变成['A short sentence', 'A second sentence'] _{'A', 'second', 'sentence', 'short'}


推荐阅读