如果給定的英陳述句子包含所有無意義的單詞,我想檢查 Python 程式。
如果句子中的所有單詞都沒有意義,則回傳 true
例如 sdfsdf sdf ssdf fsdf dsd sd
如果句子包含至少一個有意義的單詞,則回傳 false
例如你好 asdf
這是我寫的代碼。
更新了 is_meaningless 變數的代碼
import nltk
nltk.download('words')
from nltk.corpus import words
def is_sentence_meaningless(sentence):
is_meaningless = True
for word in sentence.split():
if(word in words.words()):
is_meaningless = False
break
return is_meaningless
print(is_sentence_meaningless("sss sss asdfasdf asdfasdfa asdfasfsd"))
print(is_sentence_meaningless(" sss sss asdfasdf asdfasdfa asdfasfsd TEST"))
有沒有更好的替代代碼?另外,如何將我自己的語料庫添加到其中?例如,我有幾個域特定的詞希望它回傳為真,這可能嗎?
uj5u.com熱心網友回復:
您可以使用set.difference方法(請注意,由于單詞 innltk.corpus.words主要是小寫,因此也必須使用str.lower方法,例如“hello”在但“Hello”不是):
def is_sentence_meaningless(sentence, domain_specific_words):
s_set = set(sentence.lower().split())
if s_set.difference(words.words() domain_specific_words) == s_set:
return True
return False
僅供參考,但您的功能并未按照您的解釋進行操作。
uj5u.com熱心網友回復:
鑒于單詞串列僅包含唯一的單詞,可以通過將串列轉換為集合來提高該函式的效率。
此外,您的邏輯似乎與函式的隱含目的(基于其名稱)不一致。如果在語料集中找不到句子中的任何單詞,則該句子將毫無意義。
將單詞串列轉換為集合有相當大的開銷。因此,如果要多次使用該函式,最好將其包裝在一個類中。
因此:
import nltk.corpus
class sentence_checker:
def __init__(self):
self.words = set(nltk.corpus.words.words())
def is_sentence_meaningless(self, sentence):
for word in sentence.split():
if not word in self.words:
return True
return False
sc = sentence_checker()
print(sc.is_sentence_meaningless('hello'))
print(sc.is_sentence_meaningless('hellfffo'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375712.html
上一篇:協助使用Python中的字典?
