3,386 Posted Topics
Re: Write the script to file and save it in same directory as g4. Run the file and it works by double clicking in file manager (add line [iCODE]input('Ready')[/iCODE] to see output from program) or F5 in IDLE, but it is only for simple testing. | |
Re: [code] import nltk, re from nltk.corpus import gutenberg mac = gutenberg.sents('shakespeare-macbeth.txt') x = raw_input("Please enter a sentence: ") #entering input as it is split_str=x.split() p=0 for item in split_str: if len(item)>p: s=item p=len(item) #s is the longest word in the normal input version sets = [w for w in mac … | |
Re: The first offered solution is not going to work if statistics goes over month boundary. The second solution of snippsat is quite usable if each stations data are always sorted in date order and if there is always some statistics from both given days or second day is after last … | |
Re: Make the window smaller so that You can see the output in separate window and main window same time, before clicking the button. You do start application from file manager, not from IDLE, don't you? | |
Re: Like this? [CODE]mySents = [['[', 'Emma', 'by', 'Jane', 'Austen', '1816', ']'], ['VOLUME', 'I']] print [[sent.upper() for sent in sentences ] for sentences in mySents] [/CODE] | |
Re: [QUOTE]'e' Floating point exponential format (lowercase). (3) 'E' Floating point exponential format (uppercase). (3) The alternate form causes the result to always contain a decimal point, even if no digits follow it. The precision determines the number of digits after the decimal point and defaults to 6. [/QUOTE] Straight from … | |
Re: Your number is unnormalized 0.482E1 ie 4.82. I do not understand what you want as you talk power of integer like (482**-2) but you are giving floating point number 482.0E-2 = 482 *( 10**-2) | |
Re: How about: [CODE]# sorts files by modified date, # pulls 6 most recent files, # and delete all others. #created by dan holding v0.1 (03 Aug 2010) import os, glob, time, sets root = '.' date_file_list = [] date_file_set = [] for folder in glob.glob(root): print "folder =", folder for … | |
Re: The number from file looks like number but it is string until you transform it to real number with [iCODE]int(stringnumber)[/iCODE] or [iCODE]float(stringnumber)[/iCODE] You can see the information, that operand is wrong type from the error message: [CODE]TypeError: unsupported operand type(s) for +: 'int' and 'str'[/CODE] You can confirm it by … | |
Re: Start from this: [CODE]>>> for count in range(5): print ' '*(5-count) + count* '*' * ** *** **** [/CODE] | |
Re: If you want to do it fancy way look use yo-yo for (I posted it once to code snippets but can not find it there, so here little censored version of my version of the diamond. [CODE]def diamond(width): width = width - 1 if not (width & 1) else width … | |
Re: Good solution, though I would do [CODE]if line.count(';;') < 4[/CODE] Probably lot cheaper that split every line (60[B] GB[/B] file). Also the writing out should happen when read incomplete second line which is after the short one, not when read next complete line. (The code overwrites the shorter one with … | |
Re: Check the module difflib. | |
Re: For me they sorted normally: [CODE]a={'name':1,'data':200} b={'name':2,'data':400} c=[a,b] print sorted(c,key=lambda x: x['name']) [/CODE] | |
Re: If I understand your question, you asking what number is aa in base 26: [CODE]int('aa',26) 270[/CODE] | |
Re: Why are you writing everywhere constants with int()? If you want so many globals you better move the variables in beginning of the program. Reason for '4' not working is your test: [CODE]elif int(choice) == 2 or 3[/CODE] [B]or 3[/B] is always true as 3 is not 0==False and or … | |
Re: Maybe this pattern should be made in init better or in beginnig of loading the module? At least not inside loop, I think. [CODE] leaf_pat = re.compile('%s$' % leaf)[/CODE] You could make ready list self.leaf_pats, no need probably for the words itself. This is the version i made for find … | |
Re: In regular Python 2.7 for Windows XP, this is working OK for me: [CODE]open('builtins.txt','w').write('\n'.join(dir(__builtins__))) print open('builtins.txt').read() [/CODE] | |
Re: Additionally you can use [URL="http://pypi.python.org/pypi/blist/"]blist[/URL], a faster implementation of lists for big data sets: [QUOTE]The blist is a drop-in replacement for the Python list the provides better performance when modifying large lists. The blist package also provides sortedlist, sortedset, weaksortedlist, weaksortedset, sorteddict, and btuple types. [/QUOTE] | |
Re: licence variable seems unset, maybe you mean[code] open('licence.txt').read()[/code] | |
Re: Why not clean up the XML comment with: [CODE]xml='''<Label> Hello!</Label> <!-- The above label says Hello. -- It is clear, no? Let's try spicing it up a bit. -- Add some color to it. --> <Label color="#FF0000">HI I'M RED-Y.</Label>''' print xml.replace(' -- ', ' - ') [/CODE] | |
Re: Here is my preprosessing routine for data to put it in dict from where it is simple to output the data to file open as of with [iCODE]of.write()[/iCODE] [CODE]filename='biodata.txt' datadict= dict() with open('data.csv','w') as of: data = ((ind,textline.strip().split(' ',1)) for ind,block in enumerate(open(filename).read().split('//')) for textline in block.split('XX') if ' ' … | |
Re: This code is very unpythonic, could you explain the form of output little. Maybe this should produce concordance of occurrences of words in file? My understanding from the lines: [CODE]line = RemovePunc() line_stop_words = RemoveStopWords(line) line_stop_words = StemWords(line_stop_words) index = Indexing(line_stop_words) OutputIndex(index)[/CODE] is that total effect for each line is … | |
Re: Here is example, but English messy way of "Quoting sentence." should be fixed to make this work: [CODE]import itertools as it endsentence = ".?!" filein = 'd:/test/advsh12.txt' sentences = it.groupby(open(filein).read(), lambda x: any(x.endswith(punct) for punct in endsentence)) for number,(truth, sentence) in enumerate(sentences): if truth: print number//2+1,':',previous+''.join(sentence).replace('\n',' ') previous = ''.join(sentence) … | |
Re: Are you trying to do something like this (your file I named sources.lst): [CODE]# -*- coding: utf-8 -*- import os mylist = set(' '.join(word for word in line.split()) for line in open('sources.lst').readlines() if line.strip()) print '\n'.join(sorted(mylist)) [/CODE] | |
Re: This thread is marked solved, but here is built in slice version and cleaned up version of ultimatebuster's code (calling commented out, changed to return list of words to be same format with slice solution). [CODE]filetoread = 'clozebase.txt' filetoappend = 'clozetest.txt' appendf=open(filetoappend,'a') everynth = 3 def replace_nth_word(n, text): ## cleaned … | |
Re: Something like this ?[CODE]cards=['3S', 'KD','5S', 'TC','2D','3D'] values=dict(zip('23456789TQKA',range(2,15))) print sorted(cards,key=lambda x:values[x[0]]) [/CODE] This puts the cards ordered first by value, then suit by using normal function, not lambda: [CODE]cards=['3S', 'KD','5S', 'KC','TD','3D'] values=dict(zip('23456789TQKA',range(2,15))) def sortkey(x): value,suit=x return values[value],suit print sorted(cards,key = sortkey) [/CODE] | |
Re: Yes if you need to reimplement the wheel, I would suggest that you choose Shell sort (improved insert sort), which is not so bad at all for small lists. Though for the case of 5 cards, the method is quite irrelevant as even checking all permutations for the sorted one … | |
Re: width is optional as it has default value of 0 for width (then the circle is filled with only 4 arguments) [QUOTE]pygame.draw.circle draw a circle around a point pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect Draws a circular shape on the Surface. The pos argument is the center of the … | |
Re: Those parenthesis are there because tuples are defined that way, even many times it is ok to leave them out, the comma is enough. What you mean not support overloading, what is your problem? That dash is called minus and for example 3-1==2 | |
Re: What kind of Python data you have got and code until now? Those inputs from server you have read? Are they list or what, you put only print of some kind of table (from game documentation?). | |
Re: Can you give a table of valid codes? What is valid input and desired output? I can not understand your control flow design, despite your nice explanations. You seem to be doing something very unpythonic despite one try except. Could you maybe think more general pseudo code for what you … | |
Re: Maybe you would like to see [URL="http://ipython.scipy.org/doc/rel-0.10/html/index.html"]IPython[/URL]? | |
Re: After some practise with Python idioms, you could maybe prefer this list comprehension: [CODE]test_data = """\ (231.2314,32434.344,134.2342,345.345,1234.45) (2323.567,32.6754,12323.8776,12323.575,233.5673) """ data = [ tuple( float(string_data) for string_data in eval(data_tuple)) for data_tuple in test_data.splitlines() if data_tuple.startswith('(')] for data_tuple in data: print type(data_tuple[0]),data_tuple [/CODE] | |
Re: I think you are reading in all your file with readlines, use open(filename) generator instead of data in for loop. | |
Re: It is simply variable name. I use it when I want to write "put in this variable the value, which I do not need" The for is expression to say "Do this 100 times" _ has other use, which has nothing to do the script you posted: _ variable in … | |
I found one interesting site while I was fooling around ... I mean Googling around: [url]http://python-history.blogspot.com/[/url] Maybe you would like to check it out. One of the guys blogging is quite famous in these circles: Guido van Rossum. | |
Re: Check out: [url]http://stackoverflow.com/questions/432385/sftp-in-python-platform-independent[/url] | |
Re: You have functions like class definition with self but you are speaking of module. Could you post whole class please. Or better still some pseudo code of what you want to do and accomplish. | |
Re: [CODE]## Your way l = [('a', 0), ('c', 2), ('b', 1), ('e', 4), ('d', 3)] dd= {} i = 0 while i < len(l): s = l[i] dd[s[0]] = s[1] i = i + 1 print dd #{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3} ## shorter way … | |
Re: You know about [URL="http://en.wikipedia.org/wiki/RGB_color_model"]RGB colors[/URL]? The program only changes those three components showing current values in title bar. | |
Re: [CODE]import numpy as np def f(x): return np.array([1,1,1,1,1], dtype=np.float32) * x g = np.vectorize(f, otypes=[np.ndarray]) a = np.arange(4) print(a) print repr(g(a)) [/CODE] | |
Re: dealerHand = ['3H', '7H', 'KH', 'QH', 'QH'] Two Queen of Hearts for dealer? I wonder what hand that makes ;) And, [B]Yes[/B], please [B]do not use list[/B] for variable name as function list from python becomes unusable (hidden) after that. | |
Re: I did my number checking routine before but simplest is best for me now: [CODE]def isnumeric(s): try: s=float(s) return True except ValueError: return False for text in ('one',3242,'342.342','1e6'): print text,isnumeric(text)[/CODE] Or even: [CODE]def tofloat(s): try: s=float(s) return s except ValueError: return None def isnumeric(s): return tofloat(s) is not None for … | |
Re: [CODE]from Tkinter import * class ButtonHandler: def __init__(self): self.root = Tk() self.root.geometry('600x500+200+200') self.mousedown = False self.label = Label(self.root, text=str(self.mousedown)) self.can = Canvas(self.root, width='500', height='400', bg='white') self.can.bind("<Motion>",lambda x:self.handler(x,'motion')) self.can.bind("<Button-1>",lambda x:self.handler(x,'press')) self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release')) self.label.pack() self.can.pack() self.root.mainloop() def handler(self,event,x): print('Handler %s' % x) if x == 'press': self.mousedown = True elif x == … | |
Re: > I am pretty new to the Jython world, I have a need to create the jvm custom properties but i am king on struck at array. please provide expertise suggestion.. > > Here is my code snippet : > -- snip, snip -- > I am getting syntax error, … | |
Re: Or you can go along with my calculator code example, with click to GIF buttons :) [URL="http://www.daniweb.com/code/snippet282548.html"]Simple calculator[/URL] For keyboard you would probably need more mixed up layout and could not use the modulo technique used for this two parts keyboard. | |
Re: Are you running program directly from file manager or terminal window. Some Tkinter stuff is in conflict with IDLE and does not work when run from there. Maybe you would like to add [CODE]raise SystemExit, "Bye, bye"[/CODE] to guit whole application, not only the window? | |
Re: You took out tuple and put it in two variables path and name. Now you only reconstruct it for the single parameter: [CODE] Installed.append((path,name))[/CODE] |
The End.