【问题标题】:Most efficient way to find a 3rd Person singular pronoun, a noun and a verb in a sentence in spacy在spacy的句子中找到第三人称单数代词,名词和动词的最有效方法
【发布时间】:2022-01-13 14:24:10
【问题描述】:

我有这段代码(我是 Python 新手),它运行良好,但我认为我的代码效率不高。 它检查句子是否包含第三人称单数代词(他、她或它)、名词和动词:

def findNounVerbPronoun():
    countElements = 0
    nlp = spacy.load("en_core_web_sm")
    doc = nlp("Between traveling, working, and preparing to be a mother for the first time, she is a very busy woman.")
    for token in doc:
        if token.pos_ == "NOUN":
            countElements = countElements + 1
        if token.pos_ == "PRON" and token.morph.get("Person") == ["3"] and token.morph.get("Number") == ['Sing']:
            countElements = countElements + 1
        if token.pos_ == "VERB":
            countElements = countElements + 1
    if countElements == 3:
        return True
    else:
        return False

是否有可能以比这种方式更简单的方式找出句子中是否包含动词、名词和代词(第三人称单数)?我认为我的代码并不是真正的pythonic。非常感谢!

【问题讨论】:

  • 你也会用 3 个名词加起来 3 ......你不会吗?
  • 讨厌:if countElements == 3: return True else: return False 可以简化为return countElements == 3

标签: python python-3.x spacy spacy-3


【解决方案1】:

下面的代码也应该可以工作:

def findNounVerbPronoun():
    countElements = 0
    nlp = spacy.load("en_core_web_sm")
    doc = nlp("Between traveling, working, and preparing to be a mother for the first time, she is a very busy woman.")
    for token in doc:
        print(token)
        if token.pos_ in {"NOUN","VERB"} or token.pos_ == "PRON" and token.morph.get("Person") == ["3"] and token.morph.get("Number") == ['Sing']:
            countElements+=1
            if countElements==4:
                return False #not necessary to continue
    return countElements==3

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2018-07-12
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多