2,646 Posted Topics
Re: In linux, you could use [code=text] ./test.py 2&> log.txt [/code] | |
Re: 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. | |
Re: 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 … | |
Re: 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. | |
Re: 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. | |
Re: [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 … | |
Re: 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") … | |
Re: 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] | |
![]() | Re: 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 … ![]() |
Re: 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, … | |
Re: 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 … | |
![]() | Re: 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. … |
Re: [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 … | |
Re: 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 ____ ___ ____ _ __ ____ _ ____ _____ ____ | _ … | |
Re: [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 … | |
Re: A good solution is [code=python] import webbrowser webbrowser.open("file.txt") [/code] On my system, it opens the file with gedit. | |
Re: 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": ... … | |
Re: 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', ""), … | |
Re: 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 … | |
Re: 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 … | |
Re: 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. | |
![]() | Re: [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, … |
Re: [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 … | |
Re: 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] | |
Re: from a google search [url]http://koobmeej.blogspot.com/2007/10/wxpython-multiple-panels-without-tab.html[/url] | |
Re: 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] | |
Re: 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() … | |
Re: See also the table of operator precedence in python [url]http://docs.python.org/reference/expressions.html#summary[/url]. | |
Re: It's only an idea, but don't you think [icode]sys.argv[/icode] contains the path to the double-clicked file ? | |
Re: Perhaps you should start with the output of [code=python] >>> help(str) [/code] | |
Re: Same reason. Most existing modules are for python 2. I prefer python 3, but I 'm using python 2. | |
Re: Look at the attached picture: there should be only 3 tests for the value of BMI (instead of 6 in your program). | |
Re: 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] | |
Re: 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] | |
Re: 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 … | |
Re: 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] | |
Re: 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 … | |
Re: 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 … | |
Re: 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] | |
Re: 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 … | |
Re: You could start reading this [url]http://docs.python.org/tutorial/classes.html#a-first-look-at-classes[/url] | |
Re: 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 … | |
Re: You can write [code=python] int_array = [ int(s) for s in array ] [/code] | |
Re: 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 … | |
Re: [QUOTE=jice;1183031]another alternative: [CODE] "-".join(DEVICE_IP.split(".")) [/CODE][/QUOTE] Or [icode]DEVICE_IP.replace(".", "-")[/icode] | |
Re: 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] | |
Re: [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" … | |
Re: 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. | |
Re: [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 # # # # # # … | |
Re: 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]. |
The End.