【发布时间】: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