我有一个字符串列表,我想将所有标记提取到一组标记中 - 而不是一组列表。我需要将每个 token 混合起来。
我的句子存储为“句子”中的字符串列表
所以如果尝试:
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)
最佳答案
如果您的句子是字符串,您可以将它们连接起来并再次拆分。
set(" ".join(sentences).split())
转['一个短句', '第二个句子']
进入 {'A', 'second', 'sentence', 'short'}
关于python - 从字符串列表中提取标记集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57436133/