python - 从字符串列表中提取标记集
问题描述
我有一个字符串列表,我想将所有标记提取到一组标记中 - 而不是一组列表。我需要混合所有令牌。
我的句子存储为“句子”中的字符串列表
所以如果尝试:
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 short sentence', 'A second sentence']
_{'A', 'second', 'sentence', 'short'}
推荐阅读
- azure-devops - 如何在 VSTS 中添加格式化代码规则?
- javascript - 关于浏览器事件和 HTMLElement.click() 的问题
- php - GroupBy 电子邮件并获取 Group 中最早的 created_at 日期 - Laravel Eloquent
- r - 识别电话号码,然后匹配国家代码,然后在列中分配正确的名称
- java - 关于@Service Spring Boot 中的@Spy 和@InjectMocks 的说明
- aws-appsync - 如何在 AppSync 突变上生成 Slug
- c# - 如何创建多个系列
- php - 如何在 PHP 中正确添加日期和时间(字符串)?
- javascript - 在事件处理程序中访问 React 组件参数
- c++ - [basic.start.main]/2 以“实现不应预定义主要功能”开头。这意味着什么?