我有六个列表,其中三个对应于给定的句子,另外三个列表对应于前面列表的标签。我想根据句子的顺序将这些列表压缩到OrderedDict中。
from collections import OrderedDict
sentence = 'Im fucking excited to learn your damn business'
words = ['excited', 'learn', 'business']
stopwords = ['Im', 'to', 'about', 'your']
swearwords = ['fucking', 'damn']
# Labels
words_labels = ['friendly', 'interested', 'interested']
stopwords_labels = ['stopword'] * len(stopwords)
swearwords_labels = ['sweaword'] * len(swearwords)
d = OrderedDict(zip(keys, values))
# Expected output
{
'Im': 'stopword',
'fucking': 'swearword',
'excited': 'friendly',
'to': 'stopword',
'learn': 'interested',
'your': 'stopword'
'damn': 'swearword',
'business': 'interested'
}
首先创建一个重复内容列表,语法为
stopwords_labels = ['stopword'] * len(stopwords)
然后建立列表,所有的内容和所有的标签,然后你很好
keys = [*words, *stopwords, *swearwords]
values = [*words_labels, *stopwords_labels, *swearwords_labels]
mappings = dict(zip(keys, values))
d = OrderedDict((k, mappings[k]) for k in sentence.split())
你也可以使用这种语法,它连接
keys = words + stopwords + swearwords
values = words_labels + stopwords_labels + swearwords_labels