0

How can I pass in an optional argument to user-defined function whereas when the argument is called, it filters the original data and when it’s omitted, original data is not filtered

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)

Here pos is the optional argument. The desired behaviour is that if I don’t pass in pos, it shows the most common words, whereas if I pass ‘VERB’ as pos, it shows the most common verb.

How could I make this an optional argument? Thanks

santoku
  • 3,297
  • 7
  • 48
  • 76
  • BTW, you need to get rid of those "smart-quotes", `“””` and `”””`, from your script, they aren't valid in Python. Don't use a program like Word to edit program text, use a proper programmers' editor or an IDE. – PM 2Ring Jul 16 '18 at 08:15

2 Answers2

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

Basically only filter by pos if it is truthy.

AKX
  • 152,115
  • 15
  • 115
  • 172
1

You need to assign it a default value and it automatically becomes optional.

You might need to rework the logic a bit but as for the function for example

def common_pos(doc, n, pos='VERB'):

would take whatever pos you give it but if you don't, it will become 'VERB'.

Ontamu
  • 201
  • 1
  • 5
  • The default `"VERB"` does not make sense here. OP explicitly said that it should behave differently when the parameter is not provided as opposed to when it's `"VERB"` – tobias_k Jul 16 '18 at 08:22
  • @tobias_k yes totally, at that point the answer with the solution was posted but without any explanation why or how it worked. Just wanted to give the OP the explanation of the general question of how optional variables function in python – Ontamu Jul 16 '18 at 13:46