在python函数中,如何传递要筛选的可选参数
如何将可选参数传递给用户定义函数,而当调用该参数时,它会过滤原始数据,而当忽略该参数时,则不会过滤原始数据在python函数中,如何传递要筛选的可选参数,python,Python,如何将可选参数传递给用户定义函数,而当调用该参数时,它会过滤原始数据,而当忽略该参数时,则不会过滤原始数据 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 r
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,它将显示最常见的动词
我怎么能让这成为一个可选的参数呢?谢谢
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
进行过滤
如果它是真实的,则基本上只按
pos
进行过滤。您需要为它指定一个默认值,它会自动变为可选值
您可能需要稍微修改一下逻辑,但对于函数,例如
def common_pos(doc, n, pos='VERB'):
将接受您给予它的任何内容,但如果您不接受,它将成为
“动词”
,您需要为它指定一个默认值,它将自动成为可选值
您可能需要稍微修改一下逻辑,但对于函数,例如
def common_pos(doc, n, pos='VERB'):
我会接受你给它的任何东西,但如果你不接受,它就会变成动词。顺便说一句,你需要去掉那些“智能引号”,“代码”,“代码”和“代码”,它们在Python中是无效的。不要使用类似于Word的程序来编辑程序文本,请使用适当的程序员编辑器或IDE。顺便说一句,您需要从您的脚本中删除那些“智能引号”、
“
和”
,它们在Python中无效。不要使用类似程序的Word来编辑程序文本,请使用适当的程序员编辑器或IDE。默认的“动词”
在这里没有意义。OP明确表示,当未提供参数时,它的行为应该不同于当它是“动词”
@tobias_k是的,在这一点上,给出了解决方案的答案,但没有解释为什么或如何工作。只是想给OP解释一下可选变量在python中如何起作用的一般问题默认的“动词”
在这里没有意义。OP明确表示,当未提供参数时,它的行为应该不同于当它是“动词”
@tobias_k是的,在这一点上,给出了解决方案的答案,但没有解释为什么或如何工作。只是想给OP解释一下可选变量在python中如何工作的一般问题