What could be the problem?
You're not reading the file. When you iterate over a file handle you iterate line by line. So no line will ever equal '<' or '>'.
What could be the problem?
You're not reading the file. When you iterate over a file handle you iterate line by line. So no line will ever equal '<' or '>'.
Here's another post about classes from earlier today. If you search this forum you'll find plenty of examples of working w/ classes
So you were using translate like you would use replace...
Here look:
>>> w = "'7500"
>>> int(w)
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: "'7500"
>>> w.replace("'", "")
'7500'
>>> int(w.replace("'", ""))
7500
>>> # OR
>>> int(w.strip("'"))
7500
>>>
You could really use either strip or replace here... but yeah translate is definitely not what you're looking for.
I'm trying to code a Trie in Python. Any suggestions as to where I should begin?
drjay
I suggest searching the internet using this crazy tool called the Googles.
Here was my first hit: http://en.wikipedia.org/wiki/Trie
What is "not taking 7500" ? When you do your print checks... do they print 7500 or 7, then 5, then 0, then 0 ?
Also, wtf are the translate calls there for? What are you trying to do?
To convert from a string to int or float cast it using int()
or float()
like so:
>>> s = '7500'
>>> int(s)
7500
>>> int(s) / 10
750
>>> float(s) / 5
1500.0
>>>
Well for one I suggest removing the ampersand as criteria for ignoring. Since you know that
will consistently appear you can simply replace it at the end after you join all your characters back together (which is something you omitted). Another you can replace are the double new-line characters ( \n\n
).
I also suggest using write() instead of writelines() in this case. Look over the modifications and ask about anything you don't understand:
inp=open("friends.smi", 'r')
out = []
found = False
for character in inp:
if not found:
if character == '<':
found = True
else:
out.append(character)
else:
if character == '>':
found = False
new_text = ''.join( out ).replace(' ', '').replace('\n\n', '\n')
fout = open("1.txt", "w")
fout.write(new_text)
fout.close()
Here's a possible way to get you started (note this is untested):
inp = """<FONT COLOR="ff99ff"> So hold onto your special friend </font>
- Wheels, one eight, wheels.
<SYNC Start=2474996><P Class=ENCC>
<FONT COLOR="ff99ff"> You'll need something to keep her in
<SYNC Start=2480275><P Class=ENCC>
<FONT COLOR="ff99ff"> now you stay inside this foolish grin
<SYNC Start=2486187><P Class=ENCC>
<FONT COLOR="ff99ff"> though any day your secrets end
<SYNC Start=2490682><P Class=ENCC>
<FONT COLOR="ff99ff"> but then again years may go by
<SYNC Start=2495728><P Class=ENCC> """
out = []
found = False
for character in inp:
if not found:
if character == '<':
found = True
else:
out.append(character)
else:
if character == '>':
found = False
print ''.join(out)
First of all, what version of Python are you using? If it's anything earlier than 3.0 do not use input()
, rather raw_input()
(in the same manner). It already forces the user input to string and doesn't allow for malicious things to happen.
Now, the problem in this case is likely that you don't have the text file in the same directory as the script's working directory. There's a few ways to go about this.
1: change the current working directory with os.chdir()
, and then open the file.
2: Use the absolute path to the file (meaning if the file is located under the directories \usr\foo\bar use fh = open('\usr\foo\bar\my_file.txt')
EDIT:
To make this easier you can use os.path.join
like so:
import os
my_file_path = '\usr\foo\bar'
listnum = raw_input("> ")
fn = 'VocabList.'+listnum+'.txt'
wordfile=open(os.path.join(my_file_path, fn), "r")
May I ask why four spaces are better than tabs? I was just taught this term in college to use tabs...
Tabs are unruly. Some systems translate a tab character ( \t
) to represent 4 spaces, while others 8 spaces. This could potentially be set to be anything (how about 55 spaces? Sure!) by the user; however on most standard installations it's either 4 or 8.
So let's say you're coding and using tabs and then some spaces on a line or two. You finish your epic text adventure and then send the script off to your friend. Well suddenly your script is completely broken because their system mis-aligns your indentations due to a different tab setting.
Also (and probably most importantly) Mr. Python himself, a.k.a. Guido van Rossum said he regrets ever allowing Python to accept tabs in the first place. He suggests that everyone use 4 spaces. Whoever is teaching you to use tabs needs to read PEP 8, and it wouldn't hurt for you to do the same.
It would help the forum members here to answer your question if you provided information regarding what toolkit you're using.
So how do I get the colorCode part to accept a string of letters that are in that list of six vs. just one letter.
You can loop over the user's input like this:
colorCode = raw_input("Enter the secret code: ")
for each_color in colorCode:
if each_color in ['r', 'g', 'b', 'y', 'o', 'p']:
# Pass condition
else:
print "The color choice %s is not valid" % each_color
I notice that you're still using tabs. I suggest you save yourself future heartache and switch to 4 spaces instead. Most text editors can be setup to use 4 spaces instead of tabs.
What did I screw up?
You used input
and you're not using Python30. For anything prior to Python30 you should be using raw_input
like you did for the earlier user input.
Try entering the following into input
and see what happens: 4 * 10 + 2 / 5
.
You can debug this yourself. Try pinging that ip address and port.
Helps to find root cause first
How about your actual game code? Can't really debug what the problem is without it...
My gut feeling is that you don't need to specify pygame.mixer.module; try searching this forum for vegaseat's excellent and simple py2exe script that should pull in your basic modules.
The difficulty part is "difficult" to answer as there's many ways to do it. As far as the user selecting the difficulty, you could custom roll your own message window that had multiple buttons on it (one for each difficulty) that would pop up during the call to reset()
alternately you could simply pop up a textInput field that would have the user type in the difficulty setting, or perhaps a drop-down menu on the main window or some radio buttons to choose the difficulty....
I guess how you want to do it depends on your preffered style. What's your latest code look like? I'd like to try it out and see how it feels...
i cant post it right now, because im at school, but i will later.
now that i think about it, instead of
elif
, i could just useelse
, couldn't i?
Yup that would also work. Using elif
makes Python still evaluate the statement following it. Whereas else is just a catch-all alternative
How would you guys put that in laymen's terms?
if not line.strip()
I would translate it to: if empty line:
I guess. Here's an example, basically this code is relying on the fact that Python considers an empty string, or ''
to be a False, while a non-empty string is True. Let me demonstrate:
>>> empty_line = '\n'
>>> text_line = 'Lipsum\n'
>>>
>>> empty_line.strip()
''
>>> text_line.strip()
'Lipsum'
>>> bool( empty_line.strip() )
False
>>> bool( text_line.strip() )
True
>>> if '':
... print 'Empty!'
...
>>> if not '':
... print 'Empty!'
...
Empty!
>>>
So as you can see, strip removes the new line character and any bounding white space (tabs, newline, spaces - on the far left and right of the string).
Since Python considers an empty line to be False, this code is waiting for a line that does not evaluate to False, before acting on it.
>>> lines = [ 'Not empty\n', '\n', ' Foobar\n' ]
>>> for line in lines:
... print bool( line.strip() ), '=', line.strip()
...
True = Not empty
False =
True = Foobar
>>> for line in lines:
... if line.strip():
... print 'Found a line: %s' % line.strip()
... else:
... print 'Empty line!'
...
Found a line: Not empty
Empty line!
Found a line: Foobar
>>> # Now repeat with 'not' to negate the True/False
>>> for line in lines:
... if not line.strip():
... print 'Empty line!'
... else:
... print 'Found a …
it just says that there's an error in the function and nothing else happens.
Can you explain this a little emore? Are you getting an error message? Any traceback you could post?
def playAgain(self): msgbox = wx.MessageDialog(self,message="Play Again?",style = wx.ICON_QUESTION|wx.OK|wx.CANCEL) if msgbox.ShowModal() == wx.ID_CANCEL: self.Destroy() elif msgbox.ShowModal() == wx.ID_OK: msgbox.Destroy() self.reset()
Okay the double click is because Python needs to call msgbox.ShowModal() twice here. Once to check the if, then again to check the elif (granted that the if is false). Here's a better way to write it:
def playAgain(self):
msgbox = wx.MessageDialog(self,message="Play Again?",style = wx.ICON_QUESTION|wx.OK|wx.CANCEL)
usr_ans = msgbox.ShowModal()
if usr_ans == wx.ID_CANCEL:
self.Destroy()
elif usr_ans == wx.ID_OK:
msgbox.Destroy()
self.reset()
Does that explanation make sense? HTH
Well it's hard to say without defined rules of what needs to be excluded.
Is it every "|XXX ##" that follows an instance of 'Spec ##' ? If so I would suggest using the re module to come up with a regex. It'll make it super easy to do this quickly, especially if you compile your regex. Here's the documentation, and if you need help generating the regex, post what you have so far and we'll help correct it as you go.
hi,
use parameters into drop down box in python... configure how you need....
The best way I think is to get a solid foundation in Python 2. That and read up a bit on unicode. Once done, you can just read the "What's new in python 3" page (Google it) and learn everything there is to know about using python 3.
I second that, and also suggest learning good style at the same time that you learn the language. I like PEP 8, but I think a good style is essential to good programs.
Okay, wow. It's really awesome that you're learning how easy it is to code with Python and wx and also that you're figuring out problems as quickly as your coming up with questions.
But for our sake, can you give us a "status update": Current questions and any related info
[ Pretty formatting helps us read ;) ]
It's just that this thread has now grown to 3 pages and it's difficult to tell which questions you've answered yourself or not.
ok, all questions i have had have been answered by good ol' youtube,
What?? Are there really wxPython programming tutorials on youtube or something?
I suggest downloading the 'Docs and Demos' along with your wxPython install, as it gives you a great launch pad to start writing your own GUIs by giving you sample code of almost every single type of wx object.
It's ridiculously helpful when starting wxPython.
subprocess.call(["\..\Program Files\Mozilla Firefox\firefox.exe"])
Have you verified that relative to where this script is running, \..\Program Files\Mozilla Firefox\firefox.exe
is the correct path?
I think that I've run into problems using path expansion principals within Python as it's something that I (as a mostly command-line user) take for granted. Your best bet is to probably just use the absolute path C:\\Program Files\\Mozilla Firefox\\firefox.exe
Ahah! Actually, as I typed that path out I realize what may be your mistake. In Python the \
is the escape character, so the interpreter automatically assumes any single backslashes designate an escape character (such as tab, newline, null, etc.). As a result you need to use \\
to indicate you actually want a backslash and not a special character. Here's an example to illustrate:
>>> print "\..\Program Files\Mozilla Firefox\firefox.exe"
\..\Program Files\Mozilla Firefoxirefox.exe
>>> print "\\..\\Program Files\\Mozilla Firefox\\firefox.exe"
\..\Program Files\Mozilla Firefox\firefox.exe
>>>
Hopefully that simple adjustment should clear it up and if not try using an absolute path. If neither of those suggestions work we'll do some debug work using the os.path module.
HTH
How about you use __init__.py in each of your subdirectories? Here's an illustration of the __init__.py idea from an old mailing list:
__init__.py is used for two things. One is as a flag to
indicate that the python programs in the directory are
part of a module.The other is as the module itself. Let's take a simple
example. Assume you have a directory named breakfast
which contains modules named spam.py, eggs.py,
toast.py and jam.py, and that the directory containing
breakfast is on the PYTHONPATH.If it try to import spam.py by writing
import breakfast.spam
it won't work because the breakfast directory
doesn't contain an __init__.py file.If I then add __init__.py to the breakfast directory,
the import will work, and the result will be *two*
modules loaded. The first module will be bound to
the identifier 'breakfast' in your module. It will be
completely empty except for the identifier 'spam'
which will have the spam module bound to it.This means that if the spam module contains,
for example, an identifier named "vikings", then I
can refer to it as breakfast.spam.vikings.The real kicker here is that when I say that the
first module will be completely empty, it's not
quite true. First, it will have some standard
identifiers that all modules have, and second
it will have anything you put …
What, you mean like this?
>>> def funA():
... print 'A'
...
>>> def funB():
... print 'B'
...
>>> def funC():
... print 'C'
...
>>> my_tup = ( funA, funB, funC )
>>> for each_function in my_tup:
... each_function()
...
A
B
C
>>>
Here's a way to only check against the last character (as a function):
>>> def remove_dups( word ):
... """ Remove all adjacent duplicate letters """
... new_word = word[0]
... for c in word:
... if c != new_word[-1]:
... new_word += c
... return new_word
...
>>> remove_dups ( "This phhrasse hhhhhas mmuullttiippllee repeaters" )
'This phrase has multiple repeaters'
>>> remove_dups( "Apple" )
'Aple'
>>>
I concur with Jice. In case you're simply asking us for suggestions of how to perform the same action with two different targets I would propose a for loop:
>>> for octet in [ '8', '9' ]:
... ip_add = '10.0.2.' + octet
... print 'IP Address:', ip_add
...
IP Address: 10.0.2.8
IP Address: 10.0.2.9
>>>
An even better solution would be to come up with a function that connects to a database and returns the connection object. The input to this function would be host information, login details, etc.
HTH
This is pretty straight forward:
>>> my_dict = {}
>>> for item in str1.split(','):
... key,value = item.split(':')
... if my_dict.get( key ):
... my_dict[ key ] += int( value )
... else:
... my_dict[ key ] = int( value )
...
>>> my_dict
{'a': 3, 'c': 4, 'b': 3}
>>>
If there's any piece that you don't understand.. ask and I'll explain
Is there any reason that you're using an array instead of just the built-in list ? Does your code work or is it broken?
Yes, it wrote my input to file. The code works. Maybe you have a typo in your code somewhere. But if you copy-pasted it to this forum then you have something seriously wrong with your python distro.
What version are you using?
I don't know how you could possibly be getting a tuple object... I used your code exactly and it worked just fine. A tuple is this:
a = (1, 2, 3, 4) # tuple with 4 elements
b = ('a', 'b') # tuple with 2 elements
# tuples can be iterated over like lists
for item in a:
print a
Don't know how you could possibly be getting a tuple in there.. Is that all your code?
I don't know about a "go interactive" command, but if you use pdb (python debugger) and set the pdb mark somewhere, it dumps you out into the interpreter with all your current workspace that the program has worked on so far. It's pretty simple to do, simply import pdb
at the beginning of your program and then you mark the "go interactive" portion with the command pdb.set_trace()
.
Take note, the pdb interface is kinda strange at first, but this documentation should help to qualm any trepidations you may encounter.
In the future, please use code tags when posting code in this forum, it makes your code actually readable instead of a wall of unformatted, garbled text.
Use code tags like this:
[code=python] # Code inside here
[/code]
plz some code tags about the code:
[code=python] # Put code inside here
[/code]
This will make your code readable on this forum. Also, as per forum guidelines, if you're asking a new question start a new thread, don't go digging up old threads with a similar topic.
Hmm, after taking another look at your method, you must be getting the instance and not just the contents since you're able to call the attrib
method... Have you tried using remove(item)
instead of remove(f)
?
According to documentation:
Unlike the findXYZ methods this method compares elements based on the instance identity, not on tag value or contents.
Which means that likely your iterator is returning the contents and not the instance itself.
You need to use code tags when posting code in this forum, like so:
[code=python] # Your code in here
[/code]
That will preserve your indents so that your code is readable, and will entice other forum members to actually read your post.
Here's a way to split up a list using slicing:
>>> a = [1,2,3,4,5,6,7,8,9]
>>> b = [ a[:3], a[3:6], a[6:] ]
>>> b
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
Is this what you're asking about? It helps us to be more specific in your questions and also to follow all forum guidelines so that we can better answer your questions.
The communicate method "reads all of the output and waits for child process to exit before returning" [ Source ], so in order to work with a program that expects multiple inputs you'll need to communicate with the stdin of the process as such:
proc = Popen('./Ex.sh', shell=True, stdin=PIPE, stdout=PIPE)
proc.stdout.readline()
proc.stdin.write('password\n')
proc.stdout.readline()
proc.stdin.write('123\n')
proc.stdout.readline()
...etc
I think it'd be more efficient to let Python poll the user for input and then pass those as parameters to a shell script.
Use code tags when posting code in this forum, or else nobody will be willing to help you:
[code=python] # Code goes in here
[/code]
When using the __str__
method you have to make sure that you are returning a string. Here's an example of proper usage:
>>> class foo(object):
... def __init__( self, name ):
... self.name = name
... def __str__( self ):
... return self.name
...
>>> mc = foo('bar')
>>> mc
<__main__.foo object at 0x01D24C30>
>>> print mc
bar
>>>
It sounds like you are returning something other than a string, but it's too hard to read your code without the usage of code tags. I suggest reading the forum guidelines and all posted announcements and then reposting your code and related dilemma.
EDIT: I see it now: Circle = ["Circle"]
does not create a string. ["Circle"]
is a list with a single element.
Maybe it would be easiest to uninstall and re-install Python. Perhaps you should look at adopting a new IDE as well (I'm sorry I just can't stand IDLE!)
I suggest learning the basics of Python before trying to use it as a web platform. I highly recommend dive into python, which is a free book online that is geared for programmers that already know the basics of writing code in general (control flow, data structures, etc.)
Python wasn't necessarily tailored to creating webpages, but rather to have the ability to do ANYTHING. It's a scripting language at it's core, and the syntax is designed to read like pseudo code. This makes it extremely easy for a programmer coming in from a new language (or even a complete newbie) to look at example code and instantly understand it.
That's not to say that the language is simplistic, as there are plenty of ways to obfuscate code and make it highly unreadable by combining steps, but the natural and most straight forward way is almost always instantly human-readable.
There's plenty of resources on this site as well. I suggest the sticky thread in this forum that's tailored towards beginners. It has plenty of challenges that will help you get into Python quickly. Also, don't be afraid to ask questions, as there are plenty of Python gurus on this site that are willing to help. Just remember to follow the rules and to use code tags when posting code.
I look forward to seeing you around more often, and (hopefully) being able to answer your questions.
This was the first result from googling "ubuntu install pygame": http://www.pygame.org/wiki/kubuntu
One of the best things about Ubuntu(Linux in general) is that it has such a huge open-source user base that almost every question you have has a detailed guide online of how somebody else did it.
To use code tags:
[code=python] # This is my PYTHON code # It goes between the code(=syntax) brackets
[/code]
If you use code tags your question will be easier to read, thus easier to answer by our forum members
You're more likely to get help if you follow the posting guidelines for this forum, including but not limited to using code tags, showing effort, and providing simple examples of reproducible errors.
After skimming over your crazy long post I'll give you an example of asking the user for input and using it to open a file:
import os
usr_path = raw_input( 'Please provide the path of the file: ' )
if os.path.exists( usr_path ): # Check for file existing
f = open( usr_path ) # Open for reading
lines = f.readlines() # Read in the contents
f.close() # Close the file
else:
print 'File does not exist'
HTH
Yeah, sure thing. I don't know if generating it will be as easy as your zeros
but here's an example:
>>> mtrx = [[(0,0),(0,1),(0,2),(0,3)],
... [(1,0),(1,1),(1,2),(1,3)],
... [(2,0),(2,1),(2,2),(2,3)],
... [(3,0),(3,1),(3,2),(3,3)]]
>>> mtrx[2][1]
(2, 1)
>>> mtrx[2][1][0]
2
>>> mtrx[2][1][1]
1
>>>
HTH
If you simply double click on a .py
or a .pyw
icon Python will open and run the script in a command window, just as vega mentioned above...
Keep in mind however that if your program has bugs and crashes, the command window will close as soon as Python is done executing and you'll lose the traceback.