标记化句子列表中的单词

时间:2019-10-21 15:05:15

标签: python string tokenize

我有一个单词/设备清单

appliances = ['tv', 'radio', 'oven', 'speaker']

我还有一个句子,已将其标记化。

sent = ['We have a radio in the Kitchen']
sent1 = word_tokenize[sent]

我想说的是,如果设备处于send1状态,则打印yes,否则打印no。我做了下面的工作,但一直没有得到打印。

if any(appliances) in sent1:
    print ('yes')
else:
    print ('no')

有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

尝试这样的事情。

appliances = ['tv', 'radio', 'oven', 'speaker']
sent = ['We have a radio in the Kitchen']
sent1 = list(sent[0].split())

if any([app in sent1 for app in appliances]):
    print ('yes')
else:
    print ('no')

根据@tobias_k注释进行编辑

使用惰性评估。

if any(app in sent1 for app in appliances):
    print ('yes')
else:
    print ('no')

编辑:基于@ ben121注释

如果您想在句子中看到电器,您可以这样做。

[app for app in appliances if app in sent1]