如何将可选参数传递给用户定义的函数,而调用该参数时,它将过滤原始数据,而忽略该参数,则不过滤原始数据
import spacy
from collections import Counter
nlp = spacy.load('en')
txt=“””Though the disease was eradicated decades ago, national security experts fear that stocks of the virus in labs could be released as a bioweapon.”””
doc = nlp(txt)
def common_pos(doc, n, pos):
words = [token.lemma_ for token in doc if token.is_stop != True and token.is_punct != True and token.pos_ == pos]
word_freq = Counter(words)
common_words =word_freq.most_common(n)
print(common_words)
此处pos是可选参数。理想的行为是,如果我不通过pos,则显示最常见的单词,而如果我通过“ VERB”作为pos,则显示最常见的动词。
如何使它成为可选参数?谢谢
答案 0 :(得分:3)
def common_pos(doc, n, pos=None):
words = [
token.lemma_
for token
in doc
if (
token.is_stop != True and
token.is_punct != True and
(not pos or token.pos_ == pos)
)
]
word_freq = Counter(words)
common_words =word_freq.most_common(n)
print(common_words)
如果确实存在,则基本上仅按pos
进行过滤。
答案 1 :(得分:1)
您需要为其分配一个默认值,它会自动变为可选值。
您可能需要对逻辑进行一些修改,但以功能为例
def common_pos(doc, n, pos='VERB'):
您愿意拿走pos
,但如果不付出,它将变成'VERB'
。