880 Posted Topics
Re: [CODE]def wordPop(text, n): nwords = [] words = text.split() for word in words: if (len(word) >= n): nwords.append(word) return sorted(nwords) w = 'This is a test off word lenght' print wordPop(w.lower(), 4) #->['lenght', 'test', 'this', 'word'] [/CODE] So i removed you length_compare function. [B]sorted(nwords,cmp=length_compare)[/B] So this get wrong,first off cmp … | |
Re: Always specify the exceptions to catch. Never use bare except clauses. Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug. Let you code run if you catch new exception,you can put them in [B]except(all my catch)[/B] [CODE]try: x = float(raw_input('Enter the first number: ')) y … | |
Re: [QUOTE]I'm writing a code that should extract tags from an HTML code [/QUOTE] When comes html regex may not be the right tool. Look into beautifulsoup and lxml. Read this answer by bobince about regex/html,one of the best answer i have read and funny to. [url]http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags[/url] Here is one way. … | |
Re: If you use findall you can use something simple as this. [CODE] import re text = '''\ my open verb in in red box test kk55 with me as key. ''' test_match = re.findall(r'open|red|box|with|key' ,text) print test_match #->['open', 'red', 'box', 'with', 'key'] [/CODE] Not groups but a list you can … | |
Re: Testet this out with python 2.65 This should work for python 3.xx to. Made a dir E:\1py\frezze In that dir i have 2 files. [CODE]#cx_freeze test save in dir E:\1py\freeze #date.py import time date_old = "05.26.1999" #Use strptime(time_str, format_str) to form a time tuple time_tuple = time.strptime(date_old, "%m.%d.%Y") #Use time.strftime(format_str, … | |
Re: Keep aspect ratio of the image. [CODE]from PIL import Image def resize(img,percent): ''' Resize image input image and percent | Keep aspect ratio''' w,h = img.size return img.resize(((percent*w)/100,(percent*h)/100)) if __name__ == '__main__': img = Image.open('s.jpg') #Give argumet to function image and percent resized_image = resize(img, 80) resized_image_file = 's_new.jpg' resized_image.save(resized_image_file) … | |
Re: [QUOTE]<open file 'MyText1.txt', mode 'r' at 0x15a69b0> Can someone explain? I'm on a Mac. [/QUOTE] You dont make any action for the file object. text = open(fname, "r")[B].read()[/B] Now it will read file into memory and you can print it out. So if you call "printWordFrequencies" like this it will … | |
Re: As ultimatebuster explain return get you out of a function and break get you out off a while loop. An example. [CODE] def find_father(): pass def main(): '''Main menu and info ''' while True: print 'Father finder' print '(1) 1 - Find a Father' print '(Q) Quit' choice = raw_input('Enter … | |
Re: For this i think a dictionary approach is most natural. @Beat_Slayer test your code. Edit: [QUOTE]lets suppose, South Africa.[/QUOTE] South Africa work fine in mine code. A7 is South Africa [CODE]countries = [i.strip() for i in open('countries.txt')] #Bad variables list var_list = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6'] countries_Dict = … | |
Re: [CODE]>>> x = 'car' >>> x.close() Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'str' object has no attribute 'close'[/CODE] As tony mention str has no close() method as a file object. cStringIO module has close(),or maybe you are trying to use close on what … | |
Re: This should help you. [CODE]>>> import time >>> date_old = '05/26/1999' >>> time_tuple = time.strptime(date_old, "%m/%d/%Y") >>> date_new = time.strftime("%b-%d", time_tuple) >>> date_new 'May-26' >>> [/CODE] [CODE] try: # use strptime(time_str, format_str) to form a time tuple time_tuple = time.strptime(date_old, fmt) except: #Dont use bare except try to catch specific … | |
Re: Tony rpartition soultion timeit 1000000 loops average 5.92587408782 Vega data.split()[-1] soultion 1000000 loops average 5.90504511194 Not so much differnce but vega solution is a little faster,and simpler to read and understand. That count as a plus. | |
Re: One soultion with regular expression,not hard to wirte regex for this just a couple of min. [CODE]import re text = '''\ "Id","File","Easting","Northing","Alt","Omega","Phi","Kappa","Photo","Roll","Line","Roll_line","Orient","Camera" 1800,2008308_017_079.tif,530658.110,5005704.180,2031.100000,0.351440,-0.053710,0.086470,79,2008308,17,308_17,rightX,Jen73900229d 1801,2008308_017_080.tif,531793.060,5005709.230,2033.170000,0.385000,-0.044790,-0.057690,80,2008308,17,308_17,rightX,Jen73900229d 1802,2008308_017_081.tif,532930.810,5005709.150,2032.250000,0.350180,-0.044950,0.271100,81,2008308,17,308_17,rightX,Jen73900229d 1803,2008308_017_082.tif,534066.230,5005706.620,2037.630000,0.345480,-0.036860,0.234700,82,2008308,17,308_17,rightX,Jen73900229d 1804,2008308_017_083.tif,535212.280,5005706.990,2037.470000,0.336650,-0.045540,0.306690,83,2008308,17,308_17,rightX,Jen73900229d ''' test_match = re.findall(r'\d{7}\_\d{3}\_\d{3}\.\btif\b',text) print test_match #Give us a list #Looping over item in list for item in test_match: print item '''-->Out ['2008308_017_079.tif', … | |
Re: It has been reportet as a bug,and closed with this answer. [QUOTE]This is because the negative sign is evaluated after the power. (-1)**2 works correctly.[/QUOTE] [url]http://bugs.python.org/issue4224[/url] | |
Re: Try this and it should work. [CODE]import shutil shutil.copy('c:\\test\my_file.txt', 'c:\\temp')[/CODE] You most copy files with shutil.copy. This will give you and Permission denied. You can not copy folder to folder with shutil.copy. [CODE]import shutil shutil.copy('c:\\test', 'c:\\temp')[/CODE] Use copytree. [CODE]import shutil shutil.copytree('c:\\test', 'c:\\new')[/CODE] This will copy from c:\test and make a … | |
Re: I have used 3dmax for very many years,but i have not check if there any python libraries/api for python(mayby i should do that for i am big fan of both 3dmax and python) 3dmax has it`s one language called maxscript. Here are some stuff that i have made in 3dmax. … | |
Re: You can use module fileinput for this. [CODE] import fileinput for line in fileinput.input("node.txt", inplace=1): line = line.strip() if not '1 87'in line: print line '''Out--> to node.txt Node 0 sends packet to 1 Node 0 sends packet to 3 Node 0 sends packet to 5 '''[/CODE] | |
Re: [QUOTE]In order for my code to be efficient, loops need to be terminated prematurely to prevent unnecessary iterations[/QUOTE] Yes list comprehension are faster than ordinary loop,but dont do to much Premature optimization. [QUOTE]One of the frequently repeated mantras I hear from Python veterans is, "Premature optimization is the root of … | |
Re: Here is an alternative with "endswith" thats works fine for this. [CODE]aFile = 'test.jpg' for ext in ['.txt', '.jpg', '.zip']: if aFile.lower().endswith(ext): print 'Do something'[/CODE] | |
Re: Yes a good link,i did read it that link some years ago. Here is a follow up about getters/setters that java programmers can struggle with when they try python. [url]http://tomayko.com/writings/getters-setters-fuxors[/url] Python java comparison. [url]http://pythonconquerstheuniverse.wordpress.com/category/java-and-python/[/url] | |
Re: Xp i get the same as tony. Win-7 the same. Ubuntu it work,diden`t test it to much. Virtualbox it`s easy to switch between more OS for testing. I would not use a gui-toolkit for something large. Because i think i have more control(eaiser to test) building from botton,but if you … | |
Re: There are some ting to think about when doing measurement to get it correct. Look at post from Alex Martelli and se how he dos it. As most python fans now,he knows what he is talking about. [url]http://stackoverflow.com/questions/3054604/iterate-over-the-lines-of-a-string/3054831#3054831[/url] | |
Re: You dont need a new except for every excption you whant to catch. Could look something like this. [CODE]try: file = t1.get() py_compile.compile(file) except (IOError,UnicodeDecodeError,SyntaxError): #Give message else: print "That went well!" finally: print "Cleaning up."[/CODE] | |
Re: Another way you can look at. [CODE]text = 'ARARAKHTLROGKFMBLFKKGOHMFDGRKLRNGROGINFBLMNFBAEKJGFGOQEITHRGLFDKBN' abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' textletters = list(text) abcletters = list(abc) my_list = [] for letter in abcletters: letter = textletters.count(letter) my_list.append(letter) #Now we have a list,but not easy to understand print my_list '''zip demo--> >>> l = ['a','b','c'] >>> n = [1,2,3] … | |
Re: Here i use [B]startswith('s')[/B] to get it to work on first line. Then [B]or[/B] to ger it to replace whitspace in everey new line [B]\n[/B]. This is an efficient way because you dont read hole file into memory,it work line by line. Off course on small file this dosent matter … | |
Re: Change the code with and try-except block,so it dont crash when letter is the input. [CODE]def dec(): while True: try: x = float(raw_input('enter number: ')) if x % 1 == 0: print ("The number entered must be a decimal number") else: return x except ValueError: print 'Numer only' dec()[/CODE] | |
Re: [QUOTE]inputChoice = input("Choose an option: ") #Do not need int() as input defaults to int[/QUOTE] tbone2sk this code is for python 3.x,so he need int(input()). Garrett85 make a note that you use python 3.x,most pepole use python 2.x so there is no confusion. [QUOTE]Last but not least, what is prices[choice … | |
Re: python shell File->new window Write or paste in your code To make it run-->run(F5) Get a good editor is smart like pyscripter. [url]http://code.google.com/p/pyscripter/[/url] Here you can run all code bye push the run button. | |
Re: If you want more advace look dont use tkinter. Tkinter look ugly under windows(Non-native look-and-feel) This make me not use tkinter at all,i find wxpyhon som much better an it look good under windows. Button are rounded in wxpython,or there are easy to make the look you what. And when … | |
Re: It`s better if you can use a for loop for key:value in a dicitionary. Than just 6 print statement. Here some code you can look at,with som sorted output that i see you asked about in an other post. [CODE]import pprint info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21" stat = 'id,name,country,average,board,age' info = … | |
Re: Use codetag and use english when you post in forums. Try to run this script. Maybe you have indentations problem when you type in IDLE. [CODE]secret = 1337 guess = 0 count = 0 #Help the user give number range. print 'Guess s number it`s between 0 <-> 2000 ' … | |
Re: A more clearer an Pythonic way to print the last line and some better variable name. This is done to make code more readably that always count as a plus. [B]s.replace('\n', '')[/B] you only need if you read in from a file. [CODE] s = """An Oligonucleotide is a short … | |
Re: [QUOTE]Where is python used? [/QUOTE] [url]http://www.python.org/about/quotes/[/url] [QUOTE][B]YouTube is coded mostly in Python. Why? “Development speed critical”.[/B] They use psyco, Python -> C compiler, and also C extensions, for performance critical work. They use Lighttpd for serving the video itself, for a big improvement over Apache. [/QUOTE] [QUOTE]Most of the Spotify … | |
![]() | Re: A one liner i came upp with for fun. [CODE]print 'List has duplicate item %s' % [item for item in set(L) if L.count(item) > 1] '''List has duplicate item ['oranges']''' [/CODE] |
Re: For python 3 there is [URL="http://diotavelli.net/PyQtWiki"]PyQt[/URL] Comes with [URL="http://doc.trolltech.com/4.5/designer-manual.html"]Qt designer[/URL] Look at Ene Uran post about qt-designer. [url]http://www.daniweb.com/forums/thread191210-10.html[/url] | |
Re: Do you have a question? If this is a school task try to code something yourself. What you have now is pseudocode,that maybe has some info to this task that we dont know. | |
Re: Off course python doc has info about this. This is very basic off any language. You can look at this. [CODE]i = 55 print i print(type(i)) s = 'hello' print s print(type(s)) l = [1, 2, 3] print l print(type(l)) print('string say %s i am an integer %d this is … | |
Re: [QUOTE]any one knows how to do that [/QUOTE] Yes off course many off us now how to that,you should try something yourself. Here is an explaination. For first question use [B]int(raw_input('how many questions: ')[/B] or python 3 [B]int(input('...')[/B]. This will return an integer. Then you make an empty list [B]my_list … | |
Re: [QUOTE]but what do they mean with this: directory[last,first] = number [/QUOTE] Test it out [CODE]IDLE 2.6.5 >>> directory = {} #Empty dictionary >>> last = 'hansen' >>> first = 'tom' >>> number = 22558899 >>> directory[last,first] = number >>> directory {('hansen', 'tom'): 22558899} >>> >>> dir(directory) ['__class__', '__cmp__', '__contains__', '__delattr__', … | |
Re: Just to show an alterntive print line with string formatting. Now you see it find car one time. Try to change the code so it find both cases off car in the text. [CODE]text = '''I like to drive my car. My car is black.''' search_word = 'car' index = … | |
Re: Some fun. [CODE]import re print 'Word found was found %s times' % (len([re.findall(r'\bhi\b',open('my_file.txt').read())][0]))[/CODE] Or a more readable version. [CODE]import re Search_word = 'hi' comp = r'\b%s\b' % Search_word my_file = open('my_file.txt').read() find_word = re.findall(comp, my_file) print 'Word was found %s times' % len(find_word) [/CODE] | |
Re: [url]http://www.daniweb.com/forums/thread286200.html[/url] | |
Re: Same question. [url]http://www.daniweb.com/forums/thread285652.html[/url] I give some direction in that post. This must be a school assignments therefore you should try to code yourself. You most had have some lecture about this,this is not an assignments for someone who just started with python. | |
Re: Think this is a school assignments,and your try now is really a mess. You should look more at how class in python work,read some tutorials/book or ask your teacher for help. [QUOTE]Create an Order class. The Order class should have a constructor which takes 2 parameters: a tracking number and … | |
Re: Youtube and spotify you may have heard off. [QUOTE]Youtube is written in python why? "because development speed is critical"[/QUOTE] [url]http://highscalability.com/youtube-architecture[/url] [QUOTE]Most of the Spotify backend is written in Python, with smaller parts in C and Java[/QUOTE] [url]http://www.spotify.com/int/about/jobs/software-engineer-backend/[/url] [url]http://www.python.org/about/quotes/[/url] [QUOTE]So why is most of the world's cool new software being written … | |
Re: You can simplifying your code as suggest på vegaseat. Think about design,now you have one long main function. This make code hard to read and if you want to add more code this will soon get difficult. Split code upp in more function. A shorter function is eaiser to test … | |
Re: First you can start to dowload a picture from web. [QUOTE]2. Download found Images (urllib2?)[/QUOTE] Yes can use urllib2. I have been thinking off makeing a Image crawler for a while now and maybe with a gui frontend(wxpython) Just havent getting startet yet. Here some code you can look at,download … | |
Re: That cant be the hole line? [ICODE]print "\n".join(["%s %s" %[/ICODE]. Print is a function i python 3,therefor always[ICODE] print()[/ICODE]. Just to finish that line with something so it work [CODE]>>> print ("\n".join(["%s %s" % ('a','b')])) a b >>> # some test you can look at >>> print '\n' File "<string>", … | |
Re: Example pygtk. [url]http://www.oluyede.org/blog/writing-a-widget-using-cairo-and-pygtk-28-part-2/[/url] Strong gui-toolkit for python are wxpython,PyQT,PyGTK Here is a picturer off a alrmarclock a made with wxpython for fun. [url]http://www.esnips.com/doc/e8f216fc-bf2c-4ddc-b0e2-a5b2ee97fd6b/alarm_win_7[/url] | |
Re: Kur3k that code will break because your exception handling is wrong. The code dos not what what is ask for. It check if an integer for odd/even and has no 'quit' check out. The code example should like this to make sense. [CODE]def check(number): if number % 2 == 0: … |
The End.