Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Dave Angel

On 01/-10/-28163 02:59 PM, tax botsis wrote:

I have the following txt file that has 4 fields that are tab separated: the
first is the id and the other three show the results per test.

152 TEST1 valid TEST3 good TEST2 bad
158 TEST2 bad TEST1 bad TEST4 valid
.
.
.

Based on the above txt I need to create an xls file having as headers ID,
TEST1, TEST2, TEST3, TEST4 and the values valid, bad, etc under the
corresponding column:

ID TEST1 TEST2 TEST3 TEST4
152 valid bad good
158 bad bad valid

I tried to work that out with xlwt but couldn't. Actually, I started working
on the following script but I couldn't even split the line for further
processing:

import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')

row = 0
f = open('C:/test.txt','r')
for line in f:
# separate fields by tab
L = line.rstrip().split('\t')


Looks to me like you've split a line just fine.  This line needs to be 
indented, however, so that it's inside the for loop.


What happens if you simply add a
 print L

and temporarily comment out the rest of the code?

Once you're confident about what's in L, how about if you figure out 
what data you could put into sheet.write() instead of printing it ?

Hint:  you probably want a for loop to process the list L.

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Nodes and Queues?

2011-05-11 Thread Clara Mintz

Hi all
I am sorry I am a beginner at python and I was reading my book and I came 
across the terms Nodes and Queue. I am sorry but I don't quite understand how 
they work. Is there anyone who could possibly explain them in simple terms? 
Thank you so much. 
Sincerely, 
Clara ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python program with multiple answers

2011-05-11 Thread Johnson Tran
Hi Guys, 

I've been working on a Python program where I create an 8 ball that will allow 
you to ask questions and will reply back with 20 possible answers. It will be 
continuous until the user says quit. My program works fine although I am trying 
to add something more to it, where when the user quits, it will present all the 
answers that the user got again and display them in alphabetical order...if 
anyone could point me in the right direction it'd be really helpful...my 
program so far is : (which works fine with no errros)



import random
dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For 
Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", 
"Confucious says 'No'", "Better not tell you now","Cannot predict 
now","Concentrate and ask again","My reply is no","Outlook not so good","Very 
doubtful","Outlook is good","Most likely","As I see it, yes","I do not 
understand the question")
while True:
choice = raw_input("Type 'ask' to ask a question. Type 'quit' to 
quit.\n")
if choice == "ask":
raw_input("Please enter your question:\n")
roll = random.randint(0, 10)
print dice[roll]
raw_input()
elif choice == "quit":
True = 0
raw_input()
else:
print "Error -- Try again\n"





Thanks,

JT

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nodes and Queues?

2011-05-11 Thread Patrick Sabin
A queue is a data structure, which keeps track of multiple objects. You 
can add data to a queue or you can remove it. When you remove an object 
from a queue you get the element which you have added first. Therefore, 
it is also called FIFO (First In First Out). A basic implementation 
could look like this:


class Queue:
def __init__(self):
self.items = []

def add(self, obj):
self.items.append(obj)

def remove(self):
self.items.pop(0)

Nodes are used in multiple contexts, but usually refer to objects which 
have child objects.


--
Patrick

On 2011-05-11 13:44, Clara Mintz wrote:


Hi all
I am sorry I am a beginner at python and I was reading my book and I came 
across the terms Nodes and Queue. I am sorry but I don't quite understand how 
they work. Is there anyone who could possibly explain them in simple terms? 
Thank you so much.
Sincerely,
Clara


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread Patrick Sabin

 * Create a list.
 * Each time, the user gets an answer add it to the list
 * At the end of the program: sort the list and print each element of it

- Patrick

On 2011-05-11 12:49, Johnson Tran wrote:

Hi Guys,

I've been working on a Python program where I create an 8 ball that will allow 
you to ask questions and will reply back with 20 possible answers. It will be 
continuous until the user says quit. My program works fine although I am trying 
to add something more to it, where when the user quits, it will present all the 
answers that the user got again and display them in alphabetical order...if 
anyone could point me in the right direction it'd be really helpful...my 
program so far is : (which works fine with no errros)



import random
dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", 
"Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I 
do not understand the question")
while True:
choice = raw_input("Type 'ask' to ask a question. Type 'quit' to 
quit.\n")
if choice == "ask":
raw_input("Please enter your question:\n")
roll = random.randint(0, 10)
print dice[roll]
raw_input()
elif choice == "quit":
True = 0
raw_input()
else:
print "Error -- Try again\n"





Thanks,

JT

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread Brett Ritter
On Wed, May 11, 2011 at 6:49 AM, Johnson Tran  wrote:
> I've been working on a Python program where I create an 8 ball that will 
> allow you to ask questions and will reply back with 20 possible answers.
...
> if anyone could point me in the right direction it'd be really helpful

Answer cloudy, try again later [couldn't resist]

Patrick gave a decent summary. I'd suggest for learning purposes take
each step at a time:
1) Save the questions, then once that works:
2) Save the corresponding answers, then
3) Print them, then
4) Sort them

That way if you encounter any problem it's limited in scope rather
than trying to take it all in at once.
-- 
Brett Ritter / SwiftOne
swift...@swiftone.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Walter Prins
On 11 May 2011 03:57, tax botsis  wrote:

> I tried to work that out with xlwt but couldn't. Actually, I started
> working on the following script but I couldn't even split the line for
> further processing:
>
>
OK, I've thrown together a quick sample demonstrating all the concepts you
need (obviously you need to take from this what is relevant to you):

import csv
import xlwt
import os
import sys

# Look for input file in same location as script file:
inputfilename = os.path.join(os.path.dirname(sys.argv[0]),
'tabdelimited.txt')
# Strip off the path
basefilename = os.path.basename(inputfilename)
# Strip off the extension
basefilename_noext = os.path.splitext(basefilename)[0]
# Get the path of the input file as the target output path
targetoutputpath = os.path.dirname(inputfilename)
# Generate the output filename
outputfilename =  os.path.join(targetoutputpath, basefilename_noext+'.xls')

# Create a workbook object
workbook = xlwt.Workbook()
# Add a sheet object
worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True)

# Get a CSV reader object set up for reading the input file with tab
delimiters
datareader = csv.reader(open(inputfilename, 'rb'),
delimiter='\t', quotechar='"')

# Process the file and output to Excel sheet
for rowno, row in enumerate(datareader):
for colno, colitem in enumerate(row):
worksheet.write(rowno, colno, colitem)

# Write the output file.
workbook.save(outputfilename)

# Open it via the operating system (will only work on Windows)
# On Linux/Unix you would use subprocess.Popen(['xdg-open', filename])
os.startfile(outputfilename)


The code is also available at the following URL in case the formatting gets
eaten by the mail system: http://pastebin.com/APpM7EPf

Regards

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread tee chwee liong

hi all, 
 
thanks for this sharing. when i copy and run this code, i got this error:
 
Traceback (most recent call last):
  File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
import csv
  File "C:/Python25/myscript/excel\csv.py", line 3, in 
w=csv.writer(open('output.csv','w'))
AttributeError: 'module' object has no attribute 'writer'
 
i'm using Python 2.5 and Win XP. pls help advise. 
 
thanks
tcl
 


Date: Wed, 11 May 2011 14:05:12 +0100
From: wpr...@gmail.com
To: taxbot...@gmail.com
CC: tutor@python.org
Subject: Re: [Tutor] create an xls file using data from a txt file




On 11 May 2011 03:57, tax botsis  wrote:

I tried to work that out with xlwt but couldn't. Actually, I started working on 
the following script but I couldn't even split the line for further processing:



OK, I've thrown together a quick sample demonstrating all the concepts you need 
(obviously you need to take from this what is relevant to you): 

import csv
import xlwt
import os
import sys

# Look for input file in same location as script file:
inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt')
# Strip off the path
basefilename = os.path.basename(inputfilename)
# Strip off the extension
basefilename_noext = os.path.splitext(basefilename)[0]
# Get the path of the input file as the target output path
targetoutputpath = os.path.dirname(inputfilename)
# Generate the output filename
outputfilename =  os.path.join(targetoutputpath, basefilename_noext+'.xls')
 
# Create a workbook object
workbook = xlwt.Workbook()
# Add a sheet object
worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True)

# Get a CSV reader object set up for reading the input file with tab delimiters
datareader = csv.reader(open(inputfilename, 'rb'),
delimiter='\t', quotechar='"')

# Process the file and output to Excel sheet
for rowno, row in enumerate(datareader):
for colno, colitem in enumerate(row):
worksheet.write(rowno, colno, colitem)

# Write the output file.
workbook.save(outputfilename)

# Open it via the operating system (will only work on Windows)
# On Linux/Unix you would use subprocess.Popen(['xdg-open', filename])
os.startfile(outputfilename)


The code is also available at the following URL in case the formatting gets 
eaten by the mail system: http://pastebin.com/APpM7EPf

Regards

Walter 

___ Tutor maillist - 
Tutor@python.org To unsubscribe or change subscription options: 
http://mail.python.org/mailman/listinfo/tutor   
 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 3 Level Snake Game Made using Pygame API

2011-05-11 Thread ANKUR AGGARWAL
Hey
Few weeks back I made out the basic of the snake game and released it on the
Web under the file name "hungry.py". Now I Upgraded It Into a 3 Level Game.
I test it on windows too and its working completely fine over there too.
Download the "Game.Zip" file to play all the three levels and "hungry.py" to
play the basic version. Releasing this under GPLv3 :):) Try it out and
feedback would be gr8. Here's the download link
http://code.google.com/p/hungry-snakes/downloads/list
Thanks
Ankur Aggarwal
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Walter Prins
On 11 May 2011 14:34, tee chwee liong  wrote:

>  hi all,
>
> thanks for this sharing. when i copy and run this code, i got this error:
>
> Traceback (most recent call last):
>   File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
> import csv
>   File "C:/Python25/myscript/excel\csv.py", line 3, in 
> w=csv.writer(open('output.csv','w'))
> AttributeError: 'module' object has no attribute 'writer'
>
>
Well, reading the error message, it's saying that module "csv", coming from
file "C:/Python25/myscript/excel\
csv.py" has no member "writer".  So, it seems you've called your test script
(module) "csv" which effecitvely hid the standard python "csv" module.

Try renaming your script file to something else ('testcsv.py' maybe) so its
name doesn't conflict with the standard "csv" module and try again.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread Johnson Tran
Thanks for all the replies.  But, sorry I am getting a little confused. I have 
never created a list before and am not really sure where to start. If I put a 
"answer_list=[]" before the while True: line...is this correct? Or to go by 
Brett's method, how would I go about saving the questions and answers? If I am 
only trying to make a list of the answers, I probably do not need to save the 
questions ?

This is probably completely off but tried:

import random
dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For 
Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", 
"Confucious says 'No'", "Better not tell you now","Cannot predict 
now","Concentrate and ask again","My reply is no","Outlook not so good","Very 
doubtful","Outlook is good","Most likely","As I see it, yes","I do not 
understand the question")
answer_list=[]
while True:
choice = raw_input("Type 'ask' to ask a question. Type 'quit' to 
quit.\n")
if choice == "ask":
raw_input("Please enter your question:\n")
roll = random.randint(0, len(dice))
print dice[roll]
raw_input()
elif choice == "quit":
True = 0
raw_input()
else:
print "Error -- Try again\n"
answer_list=???  <--not sure 
answer_list.sort()
print "Your answer's sorted:", answer_list

On May 11, 2011, at 5:57 AM, Brett Ritter wrote:


* Create a list.
* Each time, the user gets an answer add it to the list
* At the end of the program: sort the list and print each element of it

- Patrick



> On Wed, May 11, 2011 at 6:49 AM, Johnson Tran  wrote:
>> I've been working on a Python program where I create an 8 ball that will 
>> allow you to ask questions and will reply back with 20 possible answers.
> ...
>> if anyone could point me in the right direction it'd be really helpful
> 
> Answer cloudy, try again later [couldn't resist]
> 
> Patrick gave a decent summary. I'd suggest for learning purposes take
> each step at a time:
> 1) Save the questions, then once that works:
> 2) Save the corresponding answers, then
> 3) Print them, then
> 4) Sort them
> 
> That way if you encounter any problem it's limited in scope rather
> than trying to take it all in at once.
> -- 
> Brett Ritter / SwiftOne
> swift...@swiftone.org



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread taserian
In addition to the wise counsel you've already received, I noticed that your
randint goes from 0 to 10, but you have 20 possible outcomes in dice(). If
I'm counting correctly, it should be roll=random.randint(0, 19).

Tony R.

On Wed, May 11, 2011 at 6:49 AM, Johnson Tran  wrote:

> Hi Guys,
>
> I've been working on a Python program where I create an 8 ball that will
> allow you to ask questions and will reply back with 20 possible answers. It
> will be continuous until the user says quit. My program works fine although
> I am trying to add something more to it, where when the user quits, it will
> present all the answers that the user got again and display them in
> alphabetical order...if anyone could point me in the right direction it'd be
> really helpful...my program so far is : (which works fine with no errros)
>
>
>
> import random
> dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes",
> "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try
> again", "Confucious says 'No'", "Better not tell you now","Cannot predict
> now","Concentrate and ask again","My reply is no","Outlook not so
> good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I
> do not understand the question")
> while True:
>choice = raw_input("Type 'ask' to ask a question. Type 'quit' to
> quit.\n")
>if choice == "ask":
>raw_input("Please enter your question:\n")
>roll = random.randint(0, 10)
>print dice[roll]
>raw_input()
>elif choice == "quit":
>True = 0
>raw_input()
>else:
>print "Error -- Try again\n"
>
>
>
>
>
> Thanks,
>
> JT
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread James Reynolds
Slow day at work, so I tried something a little different mostly as a
learning exercise for myself, let me know what you all think.

I thought it would be useful to have a writer that scales and that organizes
the data. For example, you might have 20 tests one day, and 5 the next.

I broke up the data into dictionaries where the IDs were keys, and
everything that follows is a tuple of testX and result.

Instead of iterating through each column, it only writes to the columns
where data is present.

Disclaimer: I am copying and pasting into Gmail, which sometimes screws up
indents.

I also put it into pastebin, which was pretty exciting considering I have
never used it before:

http://pastebin.com/2Dke5FtX

import xlwt


class Parser:
'''
classdocs
'''


def __init__(self, test, result):
'''
Constructor
'''
self.result = result
self.test = test
self.id = int(self.test[4:])

x = open('test.txt')

id_dict = {}

for all in x:
y = all.split(" ")
y[-1] = y[-1].strip()
id_dict[y[0]] = y[1:]

max_test = 0
for key, lists in id_dict.items():
length = len(lists)/2
a = 0
parser_list = []
for items in range(length):
t = (lists[a], lists[a+1])
p = Parser(*t)
parser_list.append(p)
if max_test < p.id:
max_test = p.id
a +=2
id_dict[key] = parser_list


workbook = xlwt.Workbook()
worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True)
header = 'TEST{0}'
headers = ['ID']
range_id = range(max_test +1)
for all in range_id[1:]:
headers.append(header.format(all))

for i, colno in enumerate(headers):
print i, type(i)
worksheet.write(0, i, colno)
rowno = 1
for keys, values in id_dict.items():
worksheet.write(rowno, 0, keys)
for object_lists in values:
worksheet.write(rowno, object_lists.id , object_lists.result)
rowno +=1


workbook.save("test.xls")




On Wed, May 11, 2011 at 9:58 AM, Walter Prins  wrote:

>
>
> On 11 May 2011 14:34, tee chwee liong  wrote:
>
>>  hi all,
>>
>> thanks for this sharing. when i copy and run this code, i got this error:
>>
>> Traceback (most recent call last):
>>   File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
>> import csv
>>   File "C:/Python25/myscript/excel\csv.py", line 3, in 
>> w=csv.writer(open('output.csv','w'))
>> AttributeError: 'module' object has no attribute 'writer'
>>
>>
> Well, reading the error message, it's saying that module "csv", coming from
> file "C:/Python25/myscript/excel\
> csv.py" has no member "writer".  So, it seems you've called your test
> script (module) "csv" which effecitvely hid the standard python "csv"
> module.
>
> Try renaming your script file to something else ('testcsv.py' maybe) so its
> name doesn't conflict with the standard "csv" module and try again.
>
> Walter
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread bodsda
Hi,

I would suggest appending the dice[roll] to a new list just after the print 
statement, then in the quit block order the list and then loop over it and 
print each entry.

Hope this helps,
Bodsda
Sent from my BlackBerry® wireless device

-Original Message-
From: Johnson Tran 
Sender: tutor-bounces+bodsda=ubuntu@python.org
Date: Wed, 11 May 2011 03:49:12 
To: 
Subject: [Tutor] Python program with multiple answers

Hi Guys, 

I've been working on a Python program where I create an 8 ball that will allow 
you to ask questions and will reply back with 20 possible answers. It will be 
continuous until the user says quit. My program works fine although I am trying 
to add something more to it, where when the user quits, it will present all the 
answers that the user got again and display them in alphabetical order...if 
anyone could point me in the right direction it'd be really helpful...my 
program so far is : (which works fine with no errros)



import random
dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For 
Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", 
"Confucious says 'No'", "Better not tell you now","Cannot predict 
now","Concentrate and ask again","My reply is no","Outlook not so good","Very 
doubtful","Outlook is good","Most likely","As I see it, yes","I do not 
understand the question")
while True:
choice = raw_input("Type 'ask' to ask a question. Type 'quit' to 
quit.\n")
if choice == "ask":
raw_input("Please enter your question:\n")
roll = random.randint(0, 10)
print dice[roll]
raw_input()
elif choice == "quit":
True = 0
raw_input()
else:
print "Error -- Try again\n"





Thanks,

JT

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread Alan Gauld

"Johnson Tran"  wrote


import random
dice = ...
while True:
...
elif choice == "quit":
 True = 0
 raw_input()


Do not do this! True is supposed to be a fixed, 
constant boolean value. In fact in Python v3 you 
will get an error if you try it.


Instead use break to exit from the loop.


else:
print "Error -- Try again\n"


HTH


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Hard_way 40

2011-05-11 Thread Robert .
Hi all,

My first post ever! :)
I'm following the guide "Learn Python the Hard Way" and have reached a point
where I am struggling to understand the code and unfortunately the authors
guide hasn't cleared it up for me. (excercise 40 for reference)

The main confusion is coming from* 'cities['_find'] = find_city'* I'm not
sure what this is really doing.

>From my learning, this should add an extra item to the dict with the index
name of "_find" and the value which is returned from "find_city" function.

run I add "print cities" after the above function to try and look at how the
dict is now populated, I am still confused.

(PasteBin version to see highlighting and indents  ->
http://pastebin.com/gmngh6sc   Not sure how it will look in email)
--
cities = {'ca': 'San Fran','MI':'detroit','FL':'Jacksonville'}

cities['NY']= 'New York'
cities['OR']= 'Portland'

def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found"

cities['_find'] = find_city


while True:
print "State? (Enter to quit)",
state = raw_input("> ")

if not state:
break

city_found = cities['_find'](cities,state)
print city_found

--

Grateful for any help in explaining how this program is working and each
step it is taking.

kindest regards
Robert
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread Alan Gauld


"Johnson Tran"  wrote

If I put a "answer_list=[]" before the while True: line...is this 
correct?


Yes that creates an empty list.


only trying to make a list of the answers, I probably
do not need to save the questions ?


Correct, but


import random

answer_list=[]
while True:
choice = raw_input("Type 'ask' to ask a question. Type 
'quit' to quit.\n")

 if choice == "ask":
 raw_input("Please enter your question:\n")


You are not storing the users input so how do you know
which question was input? I'd expect to see:

question = raw_input("Please enter your question:\n")

Or is this really just a print statement? You seem to ignore
this value and just print a random question...


roll = random.randint(0, len(dice))
print dice[roll]
raw_input()


Again this does not store the answer. I'd expect:

answer_list.append( raw_input() )

This will add the answer to the list


elif choice == "quit":


break


else:
 print "Error -- Try again\n"
answer_list.sort()
print "Your answer's sorted:", answer_list


That will print the list ijncluding brackets etc, you probably want:

print "your answers sorted:"
for answer in answer_list: print answer

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nodes and Queues?

2011-05-11 Thread Alan Gauld

"Clara Mintz"  wrote

I am sorry I am a beginner at python and I was reading 
my book and I came across the terms Nodes and Queue. 
I am sorry but I don't quite understand how they work. 


Its a bit of Comp Science terminology.
A Queue is a particular type of data structure somewhat 
like a Python list but usually implemented in other 
languages using a series of Node objects each of 
which holds a value and a link to the next Node. You 
then add values to the queue by creating a new 
Node and linking it to the existing queue.


In Python you would usually implement a queue using 
the standard list and use its pop/push methods and 
indexing to simulate the behaviour without the hassle 
of creating Node classes etc.


It suggests your book is a comp science oriented book 
that happens to use Python rather than a dedicated 
Python tutorial. (That is not necessarily a bad thing, 
it will better prepare you for learning other languages 
in the future)


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python program with multiple answers

2011-05-11 Thread Prasad, Ramit
I think it should be:

import random
dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For 
Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", 
"Confucious says 'No'", "Better not tell you now","Cannot predict 
now","Concentrate and ask again","My reply is no","Outlook not so good","Very 
doubtful","Outlook is good","Most likely","As I see it, yes","I do not 
understand the question")
answer_set=set([]) # Use set because there is no need to return an answer twice 
if you are sorting alphabetically
# otherwise use answer_list = [] 
while True:
choice = raw_input("Type 'ask' to ask a question. Type 'quit' to 
quit.\n")
if choice == "ask":
raw_input("Please enter your question:\n")
roll = random.randint(0, len(dice) -1 )   #-1 because dice[20] 
will return an IndexError
answer = dice[roll]
answer_set.add(answer)
print answer
raw_input()
elif choice == "quit":
true = 0 # use LOWERCASE as to not attempt redefining True 
(yes, you can define True to equal False)
raw_input()
else:
print "Error -- Try again\n" # I think print automatically adds 
\n 
#answer_list.sort() #this works for a list but not a set
sorted_list = sorted(answer_set)
print "Your answer's sorted:", sorted_list # looks ugly
#try the following for a prettier output
print "Your answer's sorted: ", ','.join(sorted_list)

Hope that helps,
Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


-Original Message-
From: tutor-bounces+ramit.prasad=jpmchase@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of 
Johnson Tran
Sent: Wednesday, May 11, 2011 8:24 AM
To: tutor@python.org
Subject: Re: [Tutor] Python program with multiple answers

Thanks for all the replies.  But, sorry I am getting a little confused. I have 
never created a list before and am not really sure where to start. If I put a 
"answer_list=[]" before the while True: line...is this correct? Or to go by 
Brett's method, how would I go about saving the questions and answers? If I am 
only trying to make a list of the answers, I probably do not need to save the 
questions ?

This is probably completely off but tried:

import random
dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For 
Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", 
"Confucious says 'No'", "Better not tell you now","Cannot predict 
now","Concentrate and ask again","My reply is no","Outlook not so good","Very 
doubtful","Outlook is good","Most likely","As I see it, yes","I do not 
understand the question")
answer_list=[]
while True:
choice = raw_input("Type 'ask' to ask a question. Type 'quit' to 
quit.\n")
if choice == "ask":
raw_input("Please enter your question:\n")
roll = random.randint(0, len(dice))
print dice[roll]
raw_input()
elif choice == "quit":
True = 0
raw_input()
else:
print "Error -- Try again\n"
answer_list=???  <--not sure 
answer_list.sort()
print "Your answer's sorted:", answer_list

On May 11, 2011, at 5:57 AM, Brett Ritter wrote:


* Create a list.
* Each time, the user gets an answer add it to the list
* At the end of the program: sort the list and print each element of it

- Patrick



> On Wed, May 11, 2011 at 6:49 AM, Johnson Tran  wrote:
>> I've been working on a Python program where I create an 8 ball that will 
>> allow you to ask questions and will reply back with 20 possible answers.
> ...
>> if anyone could point me in the right direction it'd be really helpful
> 
> Answer cloudy, try again later [couldn't resist]
> 
> Patrick gave a decent summary. I'd suggest for learning purposes take
> each step at a time:
> 1) Save the questions, then once that works:
> 2) Save the corresponding answers, then
> 3) Print them, then
> 4) Sort them
> 
> That way if you encounter any problem it's limited in scope rather
> than trying to take it all in at once.
> -- 
> Brett Ritter / SwiftOne
> swift...@swiftone.org



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of 

Re: [Tutor] Python Hard_way 40

2011-05-11 Thread bob gailer

On 5/11/2011 11:24 AM, Robert . wrote:

Hi all,

My first post ever! :)
I'm following the guide "Learn Python the Hard Way" and have reached a 
point where I am struggling to understand the code and unfortunately 
the authors guide hasn't cleared it up for me. (excercise 40 for 
reference)


The main confusion is coming from*'cities['_find'] = find_city'* I'm 
not sure what this is really doing.


From my learning, this should add an extra item to the dict with the 
index name of "_find" and the value which is returned from "find_city" 
function.


This stores a reference to the function. The following line is the call 
to the function.


city_found = cities['_find'](cities,state)

[snip]

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Hard_way 40

2011-05-11 Thread Andre Engels
On Wed, May 11, 2011 at 5:24 PM, Robert .  wrote:
> Hi all,
>
> My first post ever! :)
> I'm following the guide "Learn Python the Hard Way" and have reached a point
> where I am struggling to understand the code and unfortunately the authors
> guide hasn't cleared it up for me. (excercise 40 for reference)
>
> The main confusion is coming from 'cities['_find'] = find_city' I'm not sure
> what this is really doing.
>
> From my learning, this should add an extra item to the dict with the index
> name of "_find" and the value which is returned from "find_city" function.

No, that would be
cities['_find'] = find_city()

When you use
cities['_find'] = find_city

the value of the extra item is _the function find_city itself_.

And thus later
city_found = cities['_find'](cities,state)

will be equivalent to
city_found = find_city(cities,state)

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Hard_way 40

2011-05-11 Thread Prasad, Ramit
>>This stores a reference to the function. The following line is the call to 
>>the function.

Just to expand. In Python, you can pass functions like you would anything else. 
So, the first line before stores the function reference find_city inside the 
dictionary cities with the key '_find'.  It then looks up the value for the key 
'_find' which returns a function and then calls the returned function with the 
arguments cities and state.


cities['_find'] = find_city
city_found = cities['_find'](cities,state)

The previous line is equivalent to
function_name = cities['_find'] # function_name is the equivalent of find_city 
now
city_found = function_name(cities, state)

And that is equivalent to:
city_found = find_city(cities, state)


Hope that helps,
Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

From: tutor-bounces+ramit.prasad=jpmchase@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of bob 
gailer
Sent: Wednesday, May 11, 2011 10:39 AM
To: Robert .
Cc: Tutor@python.org
Subject: Re: [Tutor] Python Hard_way 40

On 5/11/2011 11:24 AM, Robert . wrote:
Hi all,

My first post ever! :)
I'm following the guide "Learn Python the Hard Way" and have reached a point 
where I am struggling to understand the code and unfortunately the authors 
guide hasn't cleared it up for me. (excercise 40 for reference)

The main confusion is coming from 'cities['_find'] = find_city' I'm not sure 
what this is really doing.

>From my learning, this should add an extra item to the dict with the index 
>name of "_find" and the value which is returned from "find_city" function.

This stores a reference to the function. The following line is the call to the 
function.

city_found = cities['_find'](cities,state)

[snip]


--

Bob Gailer

919-636-4239

Chapel Hill NC


This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread James Reynolds
your "\" is a "/"

when writing out a string, such as 'C:\test.xls', the "/" is an escape in
python. So you have two choices, You can either write out path
= 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path =
r'C:\test.xls' the "r" bit tells python that the following is a regular
expression. or regex.

You can also use Walter's method above.

On Wed, May 11, 2011 at 1:10 PM, tax botsis  wrote:

> James,
> how would you save the workbook into a specific directory? I tried to run
> that:
>
> workbook.save('C:/test.xls')
>
> but I get the following error:
>
>
> Traceback (most recent call last):
>   File "", line 1, in 
> wbk.save("C:/test.xls")
>   File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 634, in save
> doc.save(filename, self.get_biff_data())
>   File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 615, in
> get_biff_data
> self.__worksheets[self.__active_sheet].selected = True
> IndexError: list index out of range
>
> Thanks
> Tax
>
>
> 2011/5/11 James Reynolds 
>
>> Slow day at work, so I tried something a little different mostly as a
>> learning exercise for myself, let me know what you all think.
>>
>> I thought it would be useful to have a writer that scales and that
>> organizes the data. For example, you might have 20 tests one day, and 5 the
>> next.
>>
>> I broke up the data into dictionaries where the IDs were keys, and
>> everything that follows is a tuple of testX and result.
>>
>> Instead of iterating through each column, it only writes to the columns
>> where data is present.
>>
>> Disclaimer: I am copying and pasting into Gmail, which sometimes screws up
>> indents.
>>
>> I also put it into pastebin, which was pretty exciting considering I have
>> never used it before:
>>
>> http://pastebin.com/2Dke5FtX
>>
>> import xlwt
>>
>>
>> class Parser:
>> '''
>> classdocs
>> '''
>>
>>
>> def __init__(self, test, result):
>> '''
>> Constructor
>> '''
>> self.result = result
>> self.test = test
>> self.id = int(self.test[4:])
>>
>> x = open('test.txt')
>>
>> id_dict = {}
>>
>> for all in x:
>> y = all.split(" ")
>> y[-1] = y[-1].strip()
>> id_dict[y[0]] = y[1:]
>>
>> max_test = 0
>> for key, lists in id_dict.items():
>> length = len(lists)/2
>> a = 0
>> parser_list = []
>> for items in range(length):
>> t = (lists[a], lists[a+1])
>> p = Parser(*t)
>> parser_list.append(p)
>> if max_test < p.id:
>> max_test = p.id
>> a +=2
>> id_dict[key] = parser_list
>>
>>
>> workbook = xlwt.Workbook()
>> worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True)
>> header = 'TEST{0}'
>> headers = ['ID']
>> range_id = range(max_test +1)
>> for all in range_id[1:]:
>> headers.append(header.format(all))
>>
>> for i, colno in enumerate(headers):
>> print i, type(i)
>> worksheet.write(0, i, colno)
>> rowno = 1
>> for keys, values in id_dict.items():
>> worksheet.write(rowno, 0, keys)
>> for object_lists in values:
>> worksheet.write(rowno, object_lists.id , object_lists.result)
>> rowno +=1
>>
>>
>> workbook.save("test.xls")
>>
>>
>>
>>
>> On Wed, May 11, 2011 at 9:58 AM, Walter Prins  wrote:
>>
>>>
>>>
>>> On 11 May 2011 14:34, tee chwee liong  wrote:
>>>
  hi all,

 thanks for this sharing. when i copy and run this code, i got this
 error:

 Traceback (most recent call last):
   File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
 import csv
   File "C:/Python25/myscript/excel\csv.py", line 3, in 
 w=csv.writer(open('output.csv','w'))
 AttributeError: 'module' object has no attribute 'writer'


>>> Well, reading the error message, it's saying that module "csv", coming
>>> from file "C:/Python25/myscript/excel\
>>> csv.py" has no member "writer".  So, it seems you've called your test
>>> script (module) "csv" which effecitvely hid the standard python "csv"
>>> module.
>>>
>>> Try renaming your script file to something else ('testcsv.py' maybe) so
>>> its name doesn't conflict with the standard "csv" module and try again.
>>>
>>> Walter
>>>
>>> ___
>>>
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Joel Goldstick
On Wed, May 11, 2011 at 1:26 PM, James Reynolds  wrote:

> your "\" is a "/"
>
> when writing out a string, such as 'C:\test.xls', the "/" is an escape in
> python. So you have two choices, You can either write out path
> = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path =
> r'C:\test.xls' the "r" bit tells python that the following is a regular
> expression. or regex.
>

r means this is 'raw data'.  Take each character literally.  Raw data does
not use \ as a prefix to an escape code.  It is just another character

>
> You can also use Walter's method above.
>
> On Wed, May 11, 2011 at 1:10 PM, tax botsis  wrote:
>
>> James,
>> how would you save the workbook into a specific directory? I tried to run
>> that:
>>
>> workbook.save('C:/test.xls')
>>
>> but I get the following error:
>>
>>
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> wbk.save("C:/test.xls")
>>   File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 634, in save
>> doc.save(filename, self.get_biff_data())
>>   File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 615, in
>> get_biff_data
>> self.__worksheets[self.__active_sheet].selected = True
>> IndexError: list index out of range
>>
>> Thanks
>> Tax
>>
>>
>> 2011/5/11 James Reynolds 
>>
>>> Slow day at work, so I tried something a little different mostly as a
>>> learning exercise for myself, let me know what you all think.
>>>
>>> I thought it would be useful to have a writer that scales and that
>>> organizes the data. For example, you might have 20 tests one day, and 5 the
>>> next.
>>>
>>> I broke up the data into dictionaries where the IDs were keys, and
>>> everything that follows is a tuple of testX and result.
>>>
>>> Instead of iterating through each column, it only writes to the columns
>>> where data is present.
>>>
>>> Disclaimer: I am copying and pasting into Gmail, which sometimes screws
>>> up indents.
>>>
>>> I also put it into pastebin, which was pretty exciting considering I have
>>> never used it before:
>>>
>>> http://pastebin.com/2Dke5FtX
>>>
>>> import xlwt
>>>
>>>
>>> class Parser:
>>> '''
>>> classdocs
>>> '''
>>>
>>>
>>> def __init__(self, test, result):
>>> '''
>>> Constructor
>>> '''
>>> self.result = result
>>> self.test = test
>>> self.id = int(self.test[4:])
>>>
>>> x = open('test.txt')
>>>
>>> id_dict = {}
>>>
>>> for all in x:
>>> y = all.split(" ")
>>> y[-1] = y[-1].strip()
>>> id_dict[y[0]] = y[1:]
>>>
>>> max_test = 0
>>> for key, lists in id_dict.items():
>>> length = len(lists)/2
>>> a = 0
>>> parser_list = []
>>> for items in range(length):
>>> t = (lists[a], lists[a+1])
>>> p = Parser(*t)
>>> parser_list.append(p)
>>> if max_test < p.id:
>>> max_test = p.id
>>> a +=2
>>> id_dict[key] = parser_list
>>>
>>>
>>> workbook = xlwt.Workbook()
>>> worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True)
>>> header = 'TEST{0}'
>>> headers = ['ID']
>>> range_id = range(max_test +1)
>>> for all in range_id[1:]:
>>> headers.append(header.format(all))
>>>
>>> for i, colno in enumerate(headers):
>>> print i, type(i)
>>> worksheet.write(0, i, colno)
>>> rowno = 1
>>> for keys, values in id_dict.items():
>>> worksheet.write(rowno, 0, keys)
>>> for object_lists in values:
>>> worksheet.write(rowno, object_lists.id , object_lists.result)
>>> rowno +=1
>>>
>>>
>>> workbook.save("test.xls")
>>>
>>>
>>>
>>>
>>> On Wed, May 11, 2011 at 9:58 AM, Walter Prins  wrote:
>>>


 On 11 May 2011 14:34, tee chwee liong  wrote:

>  hi all,
>
> thanks for this sharing. when i copy and run this code, i got this
> error:
>
> Traceback (most recent call last):
>   File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
> import csv
>   File "C:/Python25/myscript/excel\csv.py", line 3, in 
> w=csv.writer(open('output.csv','w'))
> AttributeError: 'module' object has no attribute 'writer'
>
>
 Well, reading the error message, it's saying that module "csv", coming
 from file "C:/Python25/myscript/excel\
 csv.py" has no member "writer".  So, it seems you've called your test
 script (module) "csv" which effecitvely hid the standard python "csv"
 module.

 Try renaming your script file to something else ('testcsv.py' maybe) so
 its name doesn't conflict with the standard "csv" module and try again.

 Walter

 ___

 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


>>>
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>

Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Prasad, Ramit

>your "\" is a "/"

>when writing out a string, such as 'C:\test.xls', the "/" is an escape in 
>python. So you have two choices, You can either write
out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out 
path = r'C:\test.xls' the "r" bit tells python that the following is a regular 
expression. or regex.


'/' is perfectly valid Windows separator. See the tested examples below. It 
works just fine pretty much anywhere I have ever tried it, including the 
command line. (except apparently for an MSOffice file save dialog that I tried 
just now)

>>> import xlwt
>>> workbook = xlwt.Workbook()
>>> sheet = workbook.add_sheet('test')
>>> sheet.write(0,0,'test')
>>> workbook.save('C:/test')
>>> workbook.save('C:/test.xls')
>>> workbook.save('C:\\test2.xls')
>>> workbook.save(r'C:\test3.xls')
>>>


The error he is getting may be unrelated to actually saving. I am not very 
familiar with the xlwt, but I know it does not write everything to file on the 
sheet.write() command. Save() actually does some writing and then saves the 
file. This can lead to misleading errors. I have had a similar error when 
writing non-ASCII data (and not changing the default ASCII encoding type).


Furthermore, the escape character is '\' not '/',

And r'string'  means raw string not regular expression.
"String literals may optionally be prefixed with a letter 'r' or 'R'; such 
strings are called raw strings and use different rules for interpreting 
backslash escape sequences." ~ 
http://docs.python.org/reference/lexical_analysis.html


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread James Reynolds
Yes, thank you.

Actually, I never knew that about the windows separators, since I've just
always used the '\' out of habit.



On Wed, May 11, 2011 at 2:39 PM, Prasad, Ramit wrote:

>
>
> >your "\" is a "/"
>
>
>
> >when writing out a string, such as 'C:\test.xls', the "/" is an escape in
> python. So you have two choices, You can either write
>
> out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out
> path = r'C:\test.xls' the "r" bit tells python that the following is a
> regular expression. or regex.
>
>
>
>
>
> ‘/’ is perfectly valid Windows separator. See the *tested* examples below.
> It works just fine pretty much anywhere I have ever tried it, including the
> command line. (except apparently for an MSOffice file save dialog that I
> tried just now)
>
>
>
> >>> import xlwt
>
> >>> workbook = xlwt.Workbook()
>
> >>> sheet = workbook.add_sheet('test')
>
> >>> sheet.write(0,0,'test')
>
> >>> workbook.save('C:/test')
>
> >>> workbook.save('C:/test.xls')
>
> >>> workbook.save('C:\\test2.xls')
>
> >>> workbook.save(r'C:\test3.xls')
>
> >>>
>
>
>
>
>
> The error he is getting may be unrelated to actually saving. I am not very
> familiar with the xlwt, but I know it does not write everything to file on
> the sheet.write() command. Save() actually does some writing and then saves
> the file. This can lead to misleading errors. I have had a similar error
> when writing non-ASCII data (and not changing the default ASCII encoding
> type).
>
>
>
>
>
> Furthermore, the escape character is ‘\’ not ‘/’,
>
>
>
> And r’string‘  means raw string not* *regular expression.
>
> “String literals may optionally be prefixed with a letter 'r' or 'R'; such
> strings are called *raw strings* and use different rules for interpreting
> backslash escape sequences.” ~
> http://docs.python.org/reference/lexical_analysis.html
>
>
>
>
>
> Ramit
>
>
>
>
>
>
>
> *Ramit Prasad **| JPMorgan Chase Investment Bank | Currencies Technology*
>
> *712 Main Street **| Houston, TX 77002*
>
> *work phone: 713 - 216 - 5423*
>
>
>
> This communication is for informational purposes only. It is not intended
> as an offer or solicitation for the purchase or sale of any financial
> instrument or as an official confirmation of any transaction. All market
> prices, data and other information are not warranted as to completeness or
> accuracy and are subject to change without notice. Any comments or
> statements made herein do not necessarily reflect those of JPMorgan Chase &
> Co., its subsidiaries and affiliates. This transmission may contain
> information that is privileged, confidential, legally privileged, and/or
> exempt from disclosure under applicable law. If you are not the intended
> recipient, you are hereby notified that any disclosure, copying,
> distribution, or use of the information contained herein (including any
> reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect that might
> affect any computer system into which it is received and opened, it is the
> responsibility of the recipient to ensure that it is virus free and no
> responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and
> affiliates, as applicable, for any loss or damage arising in any way from
> its use. If you received this transmission in error, please immediately
> contact the sender and destroy the material in its entirety, whether in
> electronic or hard copy format. Thank you. Please refer to
> http://www.jpmorgan.com/pages/disclosures for disclosures relating to
> European legal entities.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Steve Willoughby

On 11-May-11 12:14, James Reynolds wrote:

Actually, I never knew that about the windows separators, since I've
just always used the '\' out of habit.


If you want your code to run everywhere, you should use the functions in 
os.path to manipulate and build paths.


Otherwise, using \ all the time means your code will ONLY ever work on 
Windows.  Using / all the time means your code will work fine on Mac OS 
X, Linux, or other POSIX systems, and PROBABLY ok on Windows most of the 
time, but not on other systems.



out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can
write out path = r'C:\test.xls' the "r" bit tells python that the
following is a regular expression. or regex.


Not to be too pedantic, but since this is a tutorial list, I'll point 
out the more accurate answer so new programmers don't get a mistaken 
impression.


The 'r' string prefix does not actually mean regular expressions.  It 
means "raw string" where (almost) no backslash codes are recognized in 
the string constant, so you could say r'C:\test.xls' instead of 
'c:\\test.xls'.


Raw strings are, however, really useful for strings which hold regular 
expressions, so you see them in that context a lot.


... ah... and I just noticed that this was pointed out later in the 
thread.  Sorry for the repeat there.



‘/’ is perfectly valid Windows separator. See the *tested* examples
below. It works just fine pretty much anywhere I have ever tried it,
including the command line. (except apparently for an MSOffice file
save dialog that I tried just now)


Not... quite.  / is accepted by a number of programs, including the 
Python interpreter, which came from Unix-like systems where / is the 
directory separator.  Very old versions of MSDOS could be configured to 
use / on the command line for pretty much everything, but that has been 
deprecated for a long time now (they originally wanted / for 
command-line switches instead, so used \ for directory separators).


Core windows commands don't generally accept it, including native 
Windows applications (although sometimes they're lenient in what they 
accept).  It'll work for command-line Python script usage because it's 
*python* that allows them, not *windows*.


--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread davidheiserca


I'm not contradicting anyone, just relating my experience.

I have a large suite of Python programs that run routinely on both Windows 
and Linux systems. Some of the programs build large directory tree 
structures. I cast all directory delimiters to the forward slash "/". No 
problems.



- Original Message - 
From: "Steve Willoughby" 

To: 
Sent: Wednesday, May 11, 2011 12:48 PM
Subject: Re: [Tutor] create an xls file using data from a txt file


On 11-May-11 12:14, James Reynolds wrote:

Actually, I never knew that about the windows separators, since I've
just always used the '\' out of habit.


If you want your code to run everywhere, you should use the functions in
os.path to manipulate and build paths.

Otherwise, using \ all the time means your code will ONLY ever work on
Windows.  Using / all the time means your code will work fine on Mac OS
X, Linux, or other POSIX systems, and PROBABLY ok on Windows most of the
time, but not on other systems.


out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can
write out path = r'C:\test.xls' the "r" bit tells python that the
following is a regular expression. or regex.


Not to be too pedantic, but since this is a tutorial list, I'll point
out the more accurate answer so new programmers don't get a mistaken
impression.

The 'r' string prefix does not actually mean regular expressions.  It
means "raw string" where (almost) no backslash codes are recognized in
the string constant, so you could say r'C:\test.xls' instead of
'c:\\test.xls'.

Raw strings are, however, really useful for strings which hold regular
expressions, so you see them in that context a lot.

... ah... and I just noticed that this was pointed out later in the
thread.  Sorry for the repeat there.


‘/’ is perfectly valid Windows separator. See the *tested* examples
below. It works just fine pretty much anywhere I have ever tried it,
including the command line. (except apparently for an MSOffice file
save dialog that I tried just now)


Not... quite.  / is accepted by a number of programs, including the
Python interpreter, which came from Unix-like systems where / is the
directory separator.  Very old versions of MSDOS could be configured to
use / on the command line for pretty much everything, but that has been
deprecated for a long time now (they originally wanted / for
command-line switches instead, so used \ for directory separators).

Core windows commands don't generally accept it, including native
Windows applications (although sometimes they're lenient in what they
accept).  It'll work for command-line Python script usage because it's
*python* that allows them, not *windows*.

--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor 


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Prasad, Ramit
>Core windows commands don't generally accept it, including native 
>Windows applications (although sometimes they're lenient in what they 
>accept).  It'll work for command-line Python script usage because it's 
>*python* that allows them, not *windows*.

They work in *Windows* command prompt natively. Some apps do not work well that 
is true, but the reason that they work like this with Python is NOT because 
Python allows it but because Windows does. I highly doubt Python checks for "/" 
and converts it to "\\" (or does any complicated checking of file strings). 
YMMV for apps, but I have never had a problem with '/' on the command prompt. 
It is an important caveat to note that this behavior is not Guaranteed.

Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread Steve Willoughby

On 11-May-11 15:54, Prasad, Ramit wrote:

Core windows commands don't generally accept it, including native
Windows applications (although sometimes they're lenient in what they
accept).  It'll work for command-line Python script usage because it's
*python* that allows them, not *windows*.


They work in *Windows* command prompt natively.


Respectfully, I think you aren't clear on how command line execution 
works.  Hopefully I can help a little (yes, there are enough cases where 
it'll bite you that it's good to know this).


Some apps do not work well that is true, but the reason that theywork like this with Python is NOT because Python allows it but because 
Windows does. I highly doubt Python checks for "/" and converts it to 
"\\" (or does any complicated checking of file strings). YMMV for apps, 
but I have never had a problem with '/' on the command prompt. It is an 
important caveat to note that this behavior is not Guaranteed.


Actually, yes, that's exactly what Python (or actually the underlying 
file handling libraries it's built with) is doing on Windows.  There is 
a decades-long tradition of C compilers (et al) doing this conversion 
for the sake of all the ported Unix C programs that people wanted to run 
on Windows (or, at the time, MSDOS).


If Windows natively supported it, then you could do this:

C:\> DIR /users/fred/desktop
C:\> DEL /temp/myfile

Or try running your Python program like

C:\> /python27/python.exe scriptname.py

That doesn't work either, because Windows is NOT in any way at all 
interpreting the / characters.


So why does this work:

C:\> myscript.py /temp/myfile /users/fred/desktop

or even

C:\> \python27\python.exe myscript.py /temp/myfile

That works because Windows hands ALL of the argument strings, as-is, 
with NO interpretation, to the application to deal with.  In this case, 
the application is Python, and Python is going to the extra work to 
interpret the / characters as \ characters when you try to use them in 
open() calls and the like.


--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread tee chwee liong

excellent it works. tq
 


Date: Wed, 11 May 2011 14:58:39 +0100
Subject: Re: [Tutor] create an xls file using data from a txt file
From: wpr...@gmail.com
To: tc...@hotmail.com
CC: taxbot...@gmail.com; tutor@python.org




On 11 May 2011 14:34, tee chwee liong  wrote:


hi all, 
 
thanks for this sharing. when i copy and run this code, i got this error:
 
Traceback (most recent call last):
  File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
import csv
  File "C:/Python25/myscript/excel\csv.py", line 3, in 
w=csv.writer(open('output.csv','w'))
AttributeError: 'module' object has no attribute 'writer'



Well, reading the error message, it's saying that module "csv", coming from 
file "C:/Python25/myscript/excel\
csv.py" has no member "writer".  So, it seems you've called your test script 
(module) "csv" which effecitvely hid the standard python "csv" module.  

Try renaming your script file to something else ('testcsv.py' maybe) so its 
name doesn't conflict with the standard "csv" module and try again.

Walter
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor