I'm trying out some Text Classification tutorials here:
I don't understand the function calls in line 59 -- 65:
#creates a feature selection mechanism that uses all words
def make_full_dict(words):
return dict([(word, True) for word in words])
#tries using all words as the feature selection mechanism
print 'using all words as features'
evaluate_features(make_full_dict)
Shouldn't make_full_dict be called with a string input value for words?
Without further context, it is a bit difficult to give a complete answer to your question. It seems that the evaluate_features method takes a function as parameter; in that case, you don't need to call the function which was passed in as a parameter. Only evaluate_features should do that. If you call the function, then the return value of the function is what evaluate_features will get, rather than the function itself
If you want to see what that function is doing, add some print statements in the make_full_dict method which will help you see what words were passed to it
Related
I am trying to make a python library that allows me to make custom tkinter widgets that are more aesthetically pleasing than the built-in ones. However, I have run into a problem while defining a few functions.
The problem stems from the difference between functions like append() and str(). While the append function works as follows...
somelist = ['a', 'b', 'c']
somelist.append('d')
The str() function works like this...
somenumber = 99
somenumber_text = str(some_number)
You 'call upon' the append function by (1) stating the list that you are modifying (somelist), (2) adding a period, and (3) actually naming the append funtion itself (append()). Meanwhile you 'call upon' the str function by placing a positional argument (somenumber) within its argument area. I have no idea why there is this difference, and more importantly if there is a way to specify which method to use to 'call upon' a function that I define myself?
Thanks...
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
You really don't need to create a class, or any methods. You can make a plain-old function that's similar to bind, and just take the widget to bind as a normal parameter. For example:
def bind_multi(widget, callback, *events):
for event in events:
widget.bind(event, callback)
That means you have to call this function as bind_multi(mybutton, callback, event1, event2) instead of mybutton.bind_multi(callback, event1, event2), but there's nothing wrong with that.
I'm currently building up a library of personal debugging functions, and wanted to make a debugging print function that would provide more quality-of-life functionality than adding print(thing) lines everywhere. My current goal is to have this pseudocode function translated to Python:
def p(*args, **kwargs)
for arg in args:
print(uneval(arg), ": ", arg)
return args
The types of **kwargs and how they'd effect the output isn't as important to this question, hence why I don't use them here.
My main problem comes from trying to have some method of uneval-ing the arguments, such that I can get the string of code that actually produced them. As a use case:
>>> p(3 + 5) + 1
3 + 5: 8 # printed by p
9 # Return value of the entire expression
There's a couple of ways that I see that I can do this, and not only am I not sure if any of them work, I'm also concerned about how Pythonic any solution that actually implements these could possibly be.
Pass the argument as a string, eval it using the previous context's local identifier dictionary (how could I get that without passing it as another argument, which I definitely don't want to do?)
Figure out which line it's being run from in the .py file to extract the uneval'd strings that way (is that even possible?)
Find some metadata magic that has the information I need already in it (if it exists, which is unlikely at best).
I've made a couple of python files with functions like:
def func(a,b,c):
return a+b+c
The functions are often more complicated, but the general idea of them all are the same, receive a couple of predetermined parameters, and return the desired value.
Now, I want to make a separate GUI file for easy use of all the functions. The GUI imports all the different python scripts and via text entry fields I want to be able to give the desired parameters for each function. The problem is that the functions vary greatly in what kinds of parameters they expect, so I wanted to make each function able to return a help string to the GUI with a short explanation of what the function needs to run. In the GUI file I'm using getattr to save the desired function:
methodtocall = getattr(Nuclear, func)
I can then call the function with parameters gained for textfields, like:
methodtocall(textfield1.get(),textfield2.get())
The problem, as I said above, is that for the GUI to be useful, I need a help sentence to be printed to the GUI the moment I select a function. I tried to make an adjustment in the functions themselves, example:
def func(a,b,c):
help = "give a as string, b as list, c as integer"
if no_parameters:
return help
else:
return desired_value
The problem is that the methodtocall function gives a TypeError, since I try to launch it without any parameters: methodtocall()
The solution would be something that called the desired function the moment I select it in the GUI, and retrieves the help line for the desired function and displays it in a help textfield in the GUI, does anyone have any ideas?
Place the help text in the first unassigned string in the function definition, like this:
def func(a,b,c):
"""
This function adds three numbers.
"""
return a+b+c
Now, this text is available through the variable __doc__:
print(func.__doc__)
#
# This function adds three numbers.
#
You do not even need to call the function.
I'm starting to learn Python and I find it really interesting. I am trying to create my own module and I ran into a bump. The code goes like this:
def break_words(sentence):
words = sentence.split(' ')
return words
def sort_words (words):
sort_word=sorted(words)
return sort_word
The second function has argument words fed in by the first, and I think it should work since it has been returned, but on running filename.sort_words(words) in Python, it gives an error message of NameError:global name 'words' is not defined. And it's requiring me to define words like words=filename.break_words(sentence) before it runs the second function.
What's wrong with my code?
You should try to explain yourself better in future, it's very confusing to read and probably the reason nobody replied.
This is what I think you want to know:
import filename
words = filename.break_words('some sentence goes here')
print filename.sort_words(words)
Have you tried that?
edit:
Variables in Python are always defined in scopes, so defining one variable in a function means that it is not defined anywhere outside the function.
'return' simply returns the value of that variable to the caller.
Thanks for reading my question. As I'm still new to Python, I would like to ask about the () in Python.
def addOne(myFunc):
def addOneInside():
return myFunc() + 1
return addOneInside # <-----here is the question
#addOne
def oldFunc():
return 3
print oldFunc()
Please note that on line four, although the programme returns a function, it does not need parentheses(). Why does it NOT turn out with an error for syntax error? Thank you very much for your answers in advance!
The parentheses are used to run a function, but without them the name still refers to the function just like a variable.
return myFunc() + 1
This will evaluate the myFunc function, add 1 to its value and then return that value. The brackets are needed in order to get the function to run and return a numeric value.
return addOneInside
This is not actually running addOneInside, it is merely returning the function as a variable. You could assign this to another name and store it for later use. You could theoretically do this:
plusOne = addOneInside
plusOne()
And it will actually call the addOneInside function.
The particular instance in your initial question is known as a Decorator, and it's a way for you to perform code on the parameters being passed to your function. Your example is not very practical, but I can modify it to show a simple use case.
Let's say that you want to only have positive numbers passed to your function. If myFunc is passed a negative number, you want it to be changed to 0. You can manage this with a decorator like this.
def addOne(myFunc):
def addOneInside(num):
if num < 0:
num = 0
return myFunc(num)
return addOneInside # <-----here is the question
#addOne
def oldFunc(number):
return number
To explain, the #addOne is the decorator syntax, and it's attaching the addOneInside function to be called on the argument/s of oldFunc whenever you call it. So now here's some sample output:
oldFunc(-12)
>>> 0
oldFunc(12)
>>> 12
So now you could add logic to oldFunc that operates independently of the parameter parsing logic. You could also relatively easily change what parameters are permitted. Maybe there's also a maximum cap to hit, or you want it to log or note that the value shouldn't be negative. You can also apply this decorator to multiple functions and it will perform the same on all of them.
This blogpost explained a lot for me, so if this information is too brief to be clear, try reading the long detailed explanation there.
Your indentation in function addOne() was incorrect (I have fixed it), but I don't think that this was your problem.
If you are using Python3, then print is a function and must be called like this:
print(oldFunc())