I'm confused with the statement " print(kw,":",keywords[kw])" in the following program, in python.
def cheeseshop(kind,*arguments,**keywords):
print("--Do you have any",kind,"?")
print("--I'm sorry, we're all out of",kind)
for arg in arguments:
print(arg)
print("-"*40)
print(keywords)
keys=sorted(keywords)
print(keys)
for kw in keys:
print(kw,":",keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
The result is below:
--Do you have any Limburger ?
--I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
{'client': 'John Cleese', 'sketch': 'Cheese Shop Sketch', 'shopkeeper': 'Michael Palin'}
['client', 'shopkeeper', 'sketch']
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
In my idea, "kw" should be 'client', 'sketch' and 'shopkeeper', not numbers, then how can "kw" be the index of keywords in the statement " print(kw,":",keywords[kw])"?
To verify my idea, I also tried another program:
letters=['a','b']
for kw in letters:
print(letters[kw])
And a reasonable reply pops up:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str
That furthermore confuses me for the problem I got in the first piece of program.I think it should pop up the same error to me.
Function arguments preceded with ** are called "keyword arguments", which take named parameters when calling the function, eg: client="John Cleese" in your example. In this case, "client" is the name and "John Cleese" is the value. Arguments passed this way are placed in a dict, which is a key-value store rather than a list, which you might be familiar with in the form
x = {
"foo": "bar"
}
print x["foo"] # prints "bar"
It use the keywords utilities, it's a kind of array with a key name.
You can see the lib description, in the python documentation HERE
In fact there is a special properties of **keywords arguments that provides the right to do this.
HERE is a tutorial to use it (and also to understand it) and HERE is the stackoverflow related question.
Related
Will dynamic translation work for such a code:
const QString myText = tr("%1 Hello World").arg(someVar);
I have few doubts:
1: Will the translation entry be generated for above code (when running lupdate). If yes, will the "%1" argument part be ignored?
2: Is the above code correct ? Should the dynamic part be translated separately before using it in the argument with tr. Provided we know all possible value of someVar
When your run lupdate, you will see this in your .ts file:
<source>%1 Hello World</source>
The translator will need to know they can just ignore the '%1' part.
If someVar is a number, there is no need to do anything else. If it's a string, it will need to be translated separately.
I am a intern trying to write my first Syntax using Rascal.
While programming i ran into an error that my tutor, Riemer van Rozen, had never seen before. At the moment i am still trying to see if the problem is my code or a Rascal bug but i felt like i should report the error here.
The syntax used to parse normally and even after putting the code back the way it was before I added new stuff it still gives the same error.
My Syntax file
module Syntax
lexical Natural = [0-9]+ !>> [0-9] ;
lexical ID = [a-zA-Z][a-z0-9A-Z]* !>> [a-z0-9A-Z];
lexical String = "\"" ![\"]* "\"";
lexical Sym = [a-zA-Z.!##$%^&*];
lexical Mp = Sym*;
layout WhiteSpace = [\t-\n \r]* ;
start syntax CreatorData
= title: "title " ID title
| author: "author " ID author
| homepage: "homepage " ID homepage;
Parser
module Parser
import Syntax;
import AST;
import ParseTree;
public CreatorData load(str txt) = parse(#CreatorData, txt);
The Error
I hope someone can tell me where i am breaking my program or that i pointed out an unknown Rascal bug.
Call failed means that the call of parse failed, since the arguments you supplied, did not match any of the possible overloads of parse.
For your code, it looks like you also have an ADT called CreatorData. This is overlapping with the CreatorData syntax definition. There is a pattern documented in the tutor how to work around this challenge.
Not sure about your case, but often you can skip the ADT form, and just work on the concrete trees, but that might be something to explore in the future.
I am learning from the book Learn Python The Hard Way 3.6, by Zed Shaw
There are a series of 6 target.write commands towards the bottom of the script and he wants me to simplify them into a single target.write command using strings formats and escapes. However, I am stuck.
Here is the original code:
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename,'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines")
line1 = input("line 1:")
line2 = input("line 2:")
line3 = input("line 3:")
print("Im going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finnaly, we close it")
target.close()
So far I have tried
target.write(line1),(line2),(line3)
but this gives a logical error of only writing to one line not all three.
target.write(line1) + (line2) + (line3)
with this one I get error
'unsupported operand types for +: 'int' + 'str'
target.write(line1),\n,(line2)\n(line3),\n
with this one I get error:
unexpected character after line continuation character
(<string>,line 22)
I have been googling and searching here for answers but have not found anything. One person posted a very similar question except for Zed's 2.7 book. However I am reading Zed's 3.6 book so the answers were no help to me unfortunately.
I'm not sure what you have and haven't covered so far in the book as I'm not familiar with it but one way to do what you want is to format the string first and then pass it to the write method like this:
target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
In sketch documentation it's stated that dot and braces notations can be mixed with each other. It's even an example available:
[[context.document currentPage] deselectAllLayers];
Unfortunately, this code doesn't work in sketch and produce error if executed by "run custom script" command:
SyntaxError: Unexpected identifier 'currentPage'. Expected either a closing ']' or a ',' following an array element..
Plugin “untitled script”, line 2.
» [context.document currentPage]; «Error in command untitled script Script at path (null) does not contain a handler function named: onRun
Script executed in 0.023666s
This can be avoided by adding additional ( and ):
[[(context.document) currentPage] deselectAllLayers];
Why this happens? Is it any documentation available how exactly braces and dot notation can be mixed? Is it some error or expected behaviour?
It seems to me it's an error, but in Sketch documentation. Besides this case you showed, I couldn't find any other example where dot and braces notations are used together in the same statement, without parentheses.
The documentation page about Selections, for instance, tells that you'd use the following code to unselect everything:
var doc = context.document
[[doc currentPage] deselectAllLayers]
Follow this link and look under Clearing the selection header: http://bohemiancoding.com/sketch/support/developer/02-common-tasks/01.html
Even their example plugins don't mix both notations, as you can see here: https://github.com/BohemianCoding/ExampleSketchPlugins/blob/master/Hello%20World/Hello%20World.sketchplugin/Contents/Sketch/script.cocoascript.
In that example, context.document is also assigned to a new variable before being used within braces.
I need to specify a numeric pattern. I already made training normally.
I created a config file that has the line
user_patterns_suffix user-patterns
and the file user-patterns contains my patterns, for example:
:\d\d\d\d\d\d\d.
:\d\d\d\d\d\d\d\d\d;
!\d\d\d\d\d\d\d\d}
then I launch tesseract with the config file over a tif, and it tells me "Error: failed to insert pattern " message, for the first two patterns. It ultimately acts as if no pattern has been issued.
I need to recognize only and ever that patterns, and tried to train a language with a number-dawg file, but then, when using tesseract command, I got a segmentation fault.
I used in the number-dawg file its conversion of the above patterns:
: .
: ;
! }
The questions, as the google documentation is not clear, and I do not speak english:
the patterns file, where have to be used? I suppose number-dawg has to be used during training, but I got seg fault so couldn't try with it, and user-patterns during recognition phase, when launching Tesseract, but didn't work. Where am I doing errors?
do I need a dictionary, also, when training with number-dawg? I have a digit and punctiation only set of possible characters, and all the possible numbers in the digits, a dictionary is not possible. If I need to use dictionaries, how could I do?
Thanks in advance for help, any hint would be very appreciated