3,386 Posted Topics

Member Avatar for JDuch

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.

Member Avatar for JDuch
0
574
Member Avatar for koveras vehcna

[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 …

Member Avatar for griswolf
0
256
Member Avatar for stompper33

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 …

Member Avatar for Beat_Slayer
0
3K
Member Avatar for acrocephalus

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?

Member Avatar for TrustyTony
0
866
Member Avatar for koveras vehcna

Like this? [CODE]mySents = [['[', 'Emma', 'by', 'Jane', 'Austen', '1816', ']'], ['VOLUME', 'I']] print [[sent.upper() for sent in sentences ] for sentences in mySents] [/CODE]

Member Avatar for koveras vehcna
0
253
Member Avatar for Axelro

[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 …

Member Avatar for Axelro
0
217
Member Avatar for Axelro

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)

Member Avatar for Axelro
0
279
Member Avatar for danholding

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 …

Member Avatar for danholding
0
114
Member Avatar for zoro007

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 …

Member Avatar for zoro007
0
172
Member Avatar for Ultralisk

Start from this: [CODE]>>> for count in range(5): print ' '*(5-count) + count* '*' * ** *** **** [/CODE]

Member Avatar for TrustyTony
0
93
Member Avatar for emchom

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 …

Member Avatar for TrustyTony
0
244
Member Avatar for kadvar

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 …

Member Avatar for kadvar
0
139
Member Avatar for parijat24
Member Avatar for techie1991

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]

Member Avatar for TrustyTony
0
229
Member Avatar for -ordi-

If I understand your question, you asking what number is aa in base 26: [CODE]int('aa',26) 270[/CODE]

Member Avatar for TrustyTony
0
130
Member Avatar for KirkK

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 …

Member Avatar for TrustyTony
0
91
Member Avatar for Beat_Slayer

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 …

Member Avatar for Beat_Slayer
0
795
Member Avatar for JDuch

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]

Member Avatar for JDuch
0
188
Member Avatar for fekioh

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]

Member Avatar for ultimatebuster
0
2K
Member Avatar for acrocephalus

licence variable seems unset, maybe you mean[code] open('licence.txt').read()[/code]

Member Avatar for acrocephalus
0
433
Member Avatar for PythonNewbie2

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]

Member Avatar for snippsat
0
2K
Member Avatar for pythonbegin

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 ' ' …

Member Avatar for pythonbegin
0
1K
Member Avatar for sandhya1202

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 …

Member Avatar for Beat_Slayer
0
639
Member Avatar for koveras vehcna

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) …

Member Avatar for TrustyTony
0
1K
Member Avatar for -ordi-

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]

Member Avatar for -ordi-
0
140
Member Avatar for eldeingles

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 …

Member Avatar for TrustyTony
0
323
Member Avatar for ke24126

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]

Member Avatar for bpatt22
0
4K
Member Avatar for akls578

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 …

Member Avatar for TrustyTony
0
409
Member Avatar for lewashby

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 …

Member Avatar for lewashby
0
1K
Member Avatar for lewashby

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

Member Avatar for TrustyTony
-1
310
Member Avatar for WildBamaBoy

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?).

Member Avatar for WildBamaBoy
0
81
Member Avatar for Musing888

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 …

Member Avatar for TrustyTony
0
294
Member Avatar for deeapk_kapdi

Maybe you would like to see [URL="http://ipython.scipy.org/doc/rel-0.10/html/index.html"]IPython[/URL]?

Member Avatar for TrustyTony
0
9K
Member Avatar for ish13

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]

Member Avatar for TrustyTony
0
191
Member Avatar for fekioh

I think you are reading in all your file with readlines, use open(filename) generator instead of data in for loop.

Member Avatar for TrustyTony
0
157
Member Avatar for lewashby

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 …

Member Avatar for vegaseat
0
260
Member Avatar for TrustyTony

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.

Member Avatar for TrustyTony
0
153
Member Avatar for baki100

Check out: [url]http://stackoverflow.com/questions/432385/sftp-in-python-platform-independent[/url]

Member Avatar for baki100
0
107
Member Avatar for kuchi

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.

Member Avatar for kuchi
0
4K
Member Avatar for rahul8590

[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 …

Member Avatar for ultimatebuster
0
262
Member Avatar for lewashby

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.

Member Avatar for TrustyTony
0
223
Member Avatar for prodigenius

[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]

Member Avatar for TrustyTony
0
398
Member Avatar for yari

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.

Member Avatar for yari
0
3K
Member Avatar for lionaneesh

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 …

Member Avatar for TrustyTony
0
798
Member Avatar for bettersaid

[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 == …

Member Avatar for TrustyTony
0
192
Member Avatar for skumar244

> 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, …

Member Avatar for TrustyTony
0
96
Member Avatar for Tcll
Member Avatar for technocratic

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.

Member Avatar for vegaseat
0
5K
Member Avatar for lewashby

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?

Member Avatar for vegaseat
0
2K
Member Avatar for WildBamaBoy

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]

Member Avatar for WildBamaBoy
0
117

The End.