【问题标题】:word in list in tokenized sentence [duplicate]标记化句子中列表中的单词[重复]
【发布时间】:2019-10-21 15:05:15
【问题描述】:

我有一个单词/设备列表

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

我还有一个句子,我已经标记化了。

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

我想说,如果设备在 sent1 中,则打印是,否则打印否。我做了下面的事情,但一直没有打印出来。

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

有更好的方法吗?

【问题讨论】:

  • @JerryM。 any 返回一个布尔值

标签: python string tokenize


【解决方案1】:

试试这样的。

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 cmets 编辑

使用惰性求值。

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

编辑:基于@ben121 评论

如果你想在你的句子中看到用具,你可以这样做。

[app for app in appliances if app in sent1]

【讨论】:

  • 最好使用any(app in sent1 for app in appliances) 来利用惰性求值。
  • 谢谢。效果很好。我会怎么做才能打印列表中出现的应用程序。在这种情况下,它不是打印 yes 而是打印 radio。
  • @ben121 代码更新
猜你喜欢
  • 2014-02-17
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多