簡體   English   中英

從字符串列表中提取標記集

[英]Extracting set of tokens from list of strings

我有一個字符串列表,我想將所有標記提取到一組標記中-而不是一組列表。 我需要把所有記號混在一起。

我的句子存儲為“句子”中的字符串列表

因此,如果嘗試:

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'}

怎么樣:

set(' '.join(sentences).split())

或者您可以嘗試使用functools中的reduce。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM