2,646 Posted Topics

Member Avatar for elnaz1010
Member Avatar for Mezzck

At first sight, you should indent def savefile():... to make it a method of the App class and use [icode]filemenu.add_command(label='Save', command=self.savefile)[/icode] in the __init__ method.

Member Avatar for Mezzck
0
440
Member Avatar for eric_arambula

When you are asking a string to the user, use [icode]raw_input[/icode] instead of [icode]input[/icode] (with python 2). Here is a working version where I added a few while statements [code=python] import time print "Let's learn how to add" quit = False while not quit: x = int(input ("Give me the …

Member Avatar for eric_arambula
0
105
Member Avatar for micseydel

I don't know mac OSX, but the missing symbols are in the python library, so perhaps you should add a [icode]-lpython[/icode] somewhere, probably on the line which creates the .dynlib.

Member Avatar for micseydel
0
551
Member Avatar for anjaliua

There are many interesting google results for ontology+python and ontology+protege. I think you should check them first. Also I understand that OWL is an xml dialect, which means that it can be parsed by a python library like lxml.

Member Avatar for merchise
-1
420
Member Avatar for gorbulas

[QUOTE=gorbulas;1212235]Is there any problem with manipulating very long strings? When I say long, I'm meaning like over 100,000 characters long. I'm using examplelongString = data.readline() to get it from an html file. I then use examplelongString .find('text to find') to search for stuff. I've been trying to do it, it …

Member Avatar for TrustyTony
0
6K
Member Avatar for dbphydb

Well if the file is always found at the same address, it shouldn't be too hard to automate the task, a script could look like [code=python] from urllib2 import urlopen import subprocess as sp DOWNLOAD_URL = "http://11.12.13.27:8080/.....game.exe" DOWNLOAD_DST = "C:/....game.exe" def download(url, dst_file): content = urlopen(url).read() outfile = open(dst_file, "wb") …

Member Avatar for Udai02
0
5K
Member Avatar for daviddoria

You should probably compile with the re.DOTALL option, because the dot character does not normally match newline [code=python] m=re.compile('<test>(.*)</test>', re.DOTALL).search(MyStr) [/code]

Member Avatar for daviddoria
0
15K
Member Avatar for DancingDana

I would write it this way [code=python] import re, glob, os # compile the pattern only once and separately # avoid unnecessary groups in the pattern # escape the dot character checkedpattern = re.compile(r'checked([0-9]+?)\.txt') # avoid 'file' as a variable name for src_file in glob.glob('C:/dir1/checked*.txt'): # Find out the file …

Member Avatar for DancingDana
0
226
Member Avatar for nsutton

Here is a session with the python interpreter which should help you: [code=python] Python 2.6.4 >>> values = "9 10 J Q K A".split() >>> print(values) ['9', '10', 'J', 'Q', 'K', 'A'] >>> print list(enumerate(values)) [(0, '9'), (1, '10'), (2, 'J'), (3, 'Q'), (4, 'K'), (5, 'A')] >>> print [(i+1, …

Member Avatar for Hummdis
0
4K
Member Avatar for pietromarchy

This 'blocking readline problem' is a reccurrent question about the subprocess module. If your OS is linux, I once found a simple solution which works very well [url]http://www.daniweb.com/forums/post777876.html#post777876[/url] . For a multiplatform solution, you should try and use the Popen subclass defined in this activestate recipe [url]http://code.activestate.com/recipes/440554/[/url]. See the test …

Member Avatar for pietromarchy
0
539
Member Avatar for jazzvibes

Your matrix has 2 eigenvalues: 30 and -30. The eigenspace for the eigenvalue -30 is the space of vectors proportional to (1, 1, 1). Both Matlab and python seem to return vectors with euclidian norm 1. There are 2 possible eigenvectors with norm 1 (1/sqrt(3), 1/sqrt(3), 1/sqrt(3)) and the opposite. …

Member Avatar for Gribouillis
0
2K
Member Avatar for zzstore

[QUOTE=zzstore;1199039]Hi, Forgive me if this is a silly question as I am newbie to python. I have to pass a string that contains a few spaces to a python script. How can I get it to read as one argument? Thanks...[/QUOTE] If you are executing your script from the command …

Member Avatar for Gribouillis
0
413
Member Avatar for pythonnewbie10

I changed a few things (see the comments starting with #!!!) and added a loop. It seems to work, but there is still place for improvement. [code=python] from random import randint def menu(): while True: print """ \n\n\n\n\n\n\n ____ ___ ____ _ __ ____ _ ____ _____ ____ | _ …

Member Avatar for TrustyTony
0
180
Member Avatar for pythonnewbie10

[QUOTE=Hummdis;1191823]I agree with Tony, using the 'C' style of code, while acceptable, only adds lines and brings nothing to the table. Unlike 'C' programming, you can run actual Python code from the main body, you don't have to define functions and call them just to get results. I would suggest …

Member Avatar for TrustyTony
0
154
Member Avatar for vskumar19

A good solution is [code=python] import webbrowser webbrowser.open("file.txt") [/code] On my system, it opens the file with gedit.

Member Avatar for hondros
0
11K
Member Avatar for johnnyd1986

You could have a code structure like this [code=python] scores_file = "scores.txt" def load_scores(filename): try: return eval(open(scores_file).read()) except OSError: return [] def store_scores(filename, scores): out = open(filename, "w") out.write(repr(scores)) out.close() def main(): try: high_scores = load_scores(scores_file) user_session(high_scores) finally: store_scores(scores_file, high_scores) def user_session(scores): choice = None while choice != "0": ... …

Member Avatar for Gribouillis
0
145
Member Avatar for z 4

I suggest this simpler code. Check that it works as you expect [code=python] def cfg_wlan(self, wlan_cfg): """ Configure a new wlan for Zone Director. Input: a dictionary, supplied in DUT.py Output: none """ defaults = [ ('ssid', None), ('auth', None), ('encryption', None), ('wpa_ver', None), ('key_string', None), ('key_index', None), ('auth_server', ""), …

Member Avatar for Gribouillis
0
113
Member Avatar for TrustyTony

I like the idea of providing simple constructors for the datetime module classes. I think you should not however catch the ValueErrors which may arise. A python function is more usable when it raises an exception for wrong input, instead of printing an error message. An error message in output …

Member Avatar for TrustyTony
1
975
Member Avatar for G_S

You could write this [code=python] >>> import re >>> re.sub(r"\w+", lambda m: m.group(0).capitalize(), "the book of my friends") 'The Book Of My Friends' [/code] But, it's better to compile the regex first [code=python] import re word_re = re.compile("\w+") def _cap(match): return match.group(0).capitalize() def capitalize_all(s): return word_re.sub(_cap, s) print(capitalize_all("the book of …

Member Avatar for TrustyTony
0
893
Member Avatar for rasizzle

If you only want to read blank cells, you could use a defaultdict [code=python] from collections import defaultdict parsed_dictionary = defaultdict(lambda: None, book[0][1]) [/code] This would insert a value None if you try to read a non existent key (0,1) for example, instead of raising KeyError.

Member Avatar for Gribouillis
0
506
Member Avatar for cyon

[QUOTE=tonyjv;1193555]I do not know Pythons standard library yet well, but old BASIC hacker would do [CODE] """ Desired results Input Output 2.84 > 00:02.8 2.89 > 00:02.9 59.99 > 01:00.0 """ def convert1(t): ## desisecond rounding t= int(t*10+0.5) ## add half to get rounding to desisecond (funny unit BTW) minutes, …

Member Avatar for TrustyTony
0
559
Member Avatar for Dan08

[QUOTE=jice;1192616]Fast method, using sets : [CODE] lines=open(myfile,'r').readlines() uniquelines=set(lines) open(outfile,'w').writelines(uniquelines) [/CODE] which can be done in only one line : [CODE] open(outfile,'w').writelines(set(open(myfile,'r').readlines())) [/CODE][/QUOTE] The drawback of using sets this way is that the lines may not be written in the same order as in the input file. There are 2 functions …

Member Avatar for TrustyTony
0
4K
Member Avatar for kur3k

There is the classical [icode]zip(*list)[/icode] : [code=python] >>> matrix = [[1,2,3],[4,5,6],[7,8,9]] >>> zip(*matrix) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] [/code]

Member Avatar for TrustyTony
-1
148
Member Avatar for dpswt

from a google search [url]http://koobmeej.blogspot.com/2007/10/wxpython-multiple-panels-without-tab.html[/url]

Member Avatar for dpswt
0
178
Member Avatar for kar0lis

Why don't you set the socket's timeout to 5 and then catch the timeout error ? [code=python] sock=socket.socket(...) sock.bind((host,port)) sock.settimeout(5) try: while True: packet,address=socket.recvfrom() print packet except socket.timeout: print "socket timed out" finally: socket.close() [/code]

Member Avatar for Gribouillis
0
149
Member Avatar for kar0lis

I think you should follow a standard pattern, like the code in the socket module example [url]http://docs.python.org/py3k/library/socket.html#example[/url]. You could write something like [code=python] # python 2.6, untested code s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind( ( HOST, PORT ) ) s.listen(1) while True: conn, addr = s.accept() …

Member Avatar for kar0lis
0
147
Member Avatar for Noliving

See also the table of operator precedence in python [url]http://docs.python.org/reference/expressions.html#summary[/url].

Member Avatar for Tech B
1
210
Member Avatar for ygarin

It's only an idea, but don't you think [icode]sys.argv[/icode] contains the path to the double-clicked file ?

Member Avatar for Gribouillis
0
409
Member Avatar for kjock002

Perhaps you should start with the output of [code=python] >>> help(str) [/code]

Member Avatar for TrustyTony
-3
232
Member Avatar for jcao219

Same reason. Most existing modules are for python 2. I prefer python 3, but I 'm using python 2.

Member Avatar for hondros
0
208
Member Avatar for ITgirl2010

Look at the attached picture: there should be only 3 tests for the value of BMI (instead of 6 in your program).

Member Avatar for ITgirl2010
0
214
Member Avatar for kur3k

I found a funny module on the web, called unidecode [url]http://code.zemanta.com/tsolc/unidecode/[/url] . Here is my result [code=python] >>> from unidecode import unidecode >>> unidecode(u'ąóęśłżźćńĄÓĘŚŁŻŹĆ') 'aoeslzzcnAOESLZZC' [/code] nice, isn't it ? Edit: it's also in pypi: [url]http://pypi.python.org/pypi/Unidecode[/url]

Member Avatar for jice
0
670
Member Avatar for ihatehippies

SubBitmap is a property [code=python] >>> wx._gdi.Bitmap.SubBitmap <property object at 0x1700db8> [/code] The function called is [code=python] >>> wx._gdi.Bitmap.SubBitmap.fget <function GetSubBitmap at 0x17ae500> [/code] It's also the 'im_func' of this method [code] >>> wx._gdi.Bitmap.GetSubBitmap <unbound method Bitmap.GetSubBitmap> >>> _.im_func <function GetSubBitmap at 0x17ae500> [/code]

Member Avatar for ihatehippies
0
225
Member Avatar for ktsangop

The reason is that due to the binary representation of floating point numbers, the real number 0.1 cannot be represented exactly. On my computer [code=python] >>> "%.30f" % 0.1 '0.100000000000000005551115123126' [/code] It means that 0.1 is slightly above 0.1 ( :) ) and the remainder of the division of 23 …

Member Avatar for ktsangop
0
245
Member Avatar for kjock002

You must use an affine transformation [code=python] def my_random(a, b): r = random() return a + r * (b-a) for i in range(10): print(my_random(-.5, .5)) """my output ---> -0.0536919060601 -0.023605782825 -0.154141209554 -0.457966599001 -0.405941049256 0.152834817454 0.22015783989 -0.37435978827 0.0306778666216 0.253595405275 """ [/code]

Member Avatar for Gribouillis
0
101
Member Avatar for JJBallanger

A None value is not displayed by the python shell, as in this example [code=python] >>> value = None >>> value >>> [/code] A more useful thing to do would be to raise an exception when the number of iterations becomes too big. For example [code=python] def newton(f,x,feps,max_it): it=0 def …

Member Avatar for JJBallanger
0
231
Member Avatar for zoro007

You can use the [b]re[/b] module. See [url]http://docs.python.org/library/re.html#module-re[/url] . Here is an example [code=python] import re word_set = set(["give", "me", "bacon", "and", "eggs", "said", "the", "other", "man"]) word_re = re.compile("\w+") text = """ Draco chewed furiously at his toast, trying in vain to shut out the strong smell of bacon …

Member Avatar for sebcbien
0
164
Member Avatar for Enders_Game

I think the best solution is to raise an exception in handle_starttag when the if case is encountered. Then you write [code=python] try: parser.feed(info) parser.close() except MyCustomError: pass [/code]

Member Avatar for Enders_Game
0
170
Member Avatar for biomed

Binary search applies to ordered data. If you want to perform a binary search based on the second member, you must first sort your data according to the second member and write the result to another file. Perhaps you should describe your problem more completely: what do you expect as …

Member Avatar for sneekula
0
138
Member Avatar for the_mia_team

You could start reading this [url]http://docs.python.org/tutorial/classes.html#a-first-look-at-classes[/url]

Member Avatar for Mensa180
0
4K
Member Avatar for ultimatebuster

You could force instance attributes to have a type using a descriptor [code=python] class TypedAttribute(object): def __init__(self, tp): self.tp = tp self.name = "_typedattr_%d" % id(self) def __get__(self, obj, objtype = None): if obj is None: return self return getattr(obj, self.name) def __set__(self, obj, value): if not isinstance(value, self.tp): raise …

Member Avatar for ultimatebuster
0
567
Member Avatar for thompsonSensibl
Member Avatar for megaflo
0
8K
Member Avatar for Roberto9

If you are using python >= 2.6, you could use the Tabular class from this post [url]http://www.daniweb.com/code/snippet232375-2.html#post1025743[/url] . Here is an example use [code=python] from tabular import Tabular from random import randint suits = "CDHS" cvalues = list("AKQJ") + list(str(i) for i in range(2, 11)) deck = [cv + cs …

Member Avatar for TrustyTony
0
238
Member Avatar for vsagarmb

[QUOTE=jice;1183031]another alternative: [CODE] "-".join(DEVICE_IP.split(".")) [/CODE][/QUOTE] Or [icode]DEVICE_IP.replace(".", "-")[/icode]

Member Avatar for jice
0
2K
Member Avatar for Felulah

You can use a regex for words [code=python] import re word_re = re.compile(r"[A-Za-z]+") def count_words(sentence): return word_re.subn('', sentence)[1] print(count_words("Give me bacon and eggs, said the other man.")) [/code]

Member Avatar for Felulah
0
2K
Member Avatar for ihatehippies

[QUOTE=ihatehippies;1176187]I have a wx app that I would like to actively debug (even after it is compiled via py2exe). Is there a way to hook all methods(without having to manually add code to each one) and have it print their names' as they execute. I've looked into both the "inspect" …

Member Avatar for Gribouillis
0
369
Member Avatar for gunbuster363

You should run [code=text] $ python -i test.py [/code] It runs your program, then starts the interactive python shell. You should also have a look at python -h.

Member Avatar for gunbuster363
0
120
Member Avatar for adam321

[code=python] def maze_to_string(maze): return "\n".join(''.join(row) for row in maze) print maze_to_string(Maze) """my output ---> #################### #################### #################### ...################# ##.##..############# ##.##..##########... ##.##..##########.## ##....###########.## ##.##.######......## ##.##.######.####.## ##.##.######.####.## #####........####### ############.####### ############.####### ############.####### ############.####### ############.####### ############.####### ############.####### #################### # if you replace '' with ' ', you get # # # # # # …

Member Avatar for adam321
-2
198
Member Avatar for mattloto

You can use [icode]itertools.product(*array)[/icode], also if your want your result in a list, you write [icode]list(itertools.product(*array))[/icode].

Member Avatar for vegaseat
0
1K

The End.