【问题标题】:How to check if a given english sentence contains all non-meaning words using python?如何使用python检查给定的英文句子是否包含所有无意义的单词?
【发布时间】:2021-12-06 08:07:15
【问题描述】:

如果给定的英文句子包含所有无意义的单词,我想检查 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"))

此代码是否有更好的替代方法?另外,我怎样才能添加我自己的语料库呢?例如,我希望它返回真实的域特定单词很少,这可能吗?

【问题讨论】:

    标签: python python-3.x dictionary nltk


    【解决方案1】:

    您可以使用set.difference 方法(请注意,由于nltk.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
    

    仅供参考,但您的功能与您的解释不符。

    【讨论】:

    • 根据 Python 的版本,您可以使用 - 运算符 e。 gset(sentence.split()) - words.words()
    • @CutePoison 你是对的。 - 也是有效的。
    • @ManlaiA 你能确认你的代码是否有效吗?给 AttributeError: 'list' 对象没有属性 'difference'
    【解决方案2】:

    鉴于单词列表仅包含唯一单词,通过将列表转换为集合可以使函数更加高效。

    此外,您的逻辑似乎与函数的隐含目的不一致(基于其名称)。如果在语料集中找不到句子中的任何单词,则该句子将毫无意义。

    将单词列表转换为集合有相当大的开销。因此,如果要多次使用该函数,最好将其包装在一个类中。

    因此:

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

    【讨论】:

    • print(sc.is_sentence_meaningless('sssss asas')) 应该返回 False,但返回 true
    • 记住,这个函数叫做is_sentence_meaningless。那句话是没有意义的,所以它返回 True
    • 在所有情况下它都返回 True。
    • 尝试传递句子 'hello world' 它将返回 False - 即,它不是毫无意义的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多