Re: [Tutor] Tutor Digest, Vol 93, Issue 117

2011-11-20 Thread Mic


Message: 4
Date: Sat, 19 Nov 2011 23:18:01 +
From: Alan Gauld 
To: tutor@python.org
Subject: Re: [Tutor] Can I shorten this code?
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1; format=flowed


Most peoples code could be shortened. And most of it would be the worse
for it. There are a few occasions when shortening makes sense,
especially if its all repeated lines or just plain superflous code.
But, in general, aim to write readable code, not just short code.





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




**



Thanks for your detailed answer, it is really appreciated :)
I understand now that it is really useful to have describing
names for a function so others can read/understand the code.

I have done my best to make the code more readable now. Here is the result.


from tkinter import*

button1_color="green"
button1_value=False

button2_color="green"
button2_value=False


class Window(Frame):
   def __init__(self,master):
   super (Window,self).__init__(master)
   self.grid()
   self.create_widgets()

   def create_widgets(self):

   #Creates hello button1
   self.hello_bttn1=Button(self,bg=button1_color, text="Hi_1", 
command=self.button1_clicked)

   self.hello_bttn1.grid()

   #Creates hello button2
   self.hello_bttn2=Button(self,bg=button2_color, text="Hi_1", 
command=self.button2_clicked)

   self.hello_bttn2.grid()



   def button1_clicked(self):
   """ This method runs if button one is clicked"""

   def change_button1_value():
   global button1_value
   button1_value=not button1_value

   change_button1_value()

   if button1_value:

   self.hello_bttn1.configure(bg="red", text="Hi_2")

   def change_button1_color_red():
   global button1_color
   button1_color=("red")
   change_button1_color_red()




   else:
   self.hello_bttn1.configure(bg="green", text="Hi_1")




   def change_button1_color_green():
   global button1_color
   button1_color=("green")
   change_button1_color_green()

   #-

   def button2_clicked(self):
   """This method runs if button two is clicked"""

   def change_button2_value():
   global button2_value
   button2_value=not button2_value

   change_button2_value()

   if button2_value:

   self.hello_bttn2.configure(bg="red", text="Hi_2")



   def change_button2_color_red():
   global button2_color
   button2_color=("red")
   change_button2_color_red()




   else:
   self.hello_bttn2.configure(text="Hi_1", bg="green")




   def change_button2_color_green():
   global button2_color
   button2_color=("green")
   change_button2_color_green()












root=Tk()
root.title("Test")
root.geometry("200x200")
app=Window(root)
root.mainloop()



However, I did not understand this part of your suggestions:

def change_global2_1():

global value1
value1=("green")


And this is completely redundant since it does exactly the same as the
other function, all you need is a parameter when you call it, like so:

def setValue1(val):
 global value1
 value1 = val


change_global2_1()


And this becomes

setValue1("green")

But ultimately you could just have set it directly in your outer
function, it's hardly worth the cost of defining a function, unless you
intend to add more to it later.


def change_value_hellobttn2(self):


All of the above comments apply here too.




Generally you build a data table with all the config parameters that
will varty then you build a loop to read the values from the data table.
Store the created buttons in a list or dictionary.

I must admit that I have never heard of a "data table" before. Is this easy 
to do, for

a beginner like me?


Thanks for your answers!



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


[Tutor] Help with error in ski game

2011-11-20 Thread Chloe Beck

Hi,
I've just begun trying to teach myself how to program with Python. I'm 
currently working through the book 'Hello World, Computer programming 
for kids and other beginners' and am stuck on one of the exercises.


The exercise is a take on the SkiFree game.

The error message I get is as follows and occurs in game play when my 
skier goes to the far left of the screen:


Traceback (most recent call last):
  File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 99, in 
skier.move(speed)
  File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 28, in move
if self.rect.centerx < 20:  self.rect.centrex = 20
AttributeError: 'pygame.Rect' object has no attribute 'centrex'

I can't for the life of me figure out what i've done wrong but as i said 
i am very new to this all. Enjoying it so far though :)

I'm using Python 2.5 on a Mac

Below is the code. Any help is greatly appreciated as is any advice on 
new things to try when attempting to learn Python



Regards Chloe







import pygame, sys, random

skier_images = ["skier_down.png", "skier_right1.png",
"skier_right2.png", "skier_left2.png",
"skier_left1.png"]

class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320,100]
self.angle = 0

def turn(self, direction):
self.angle = self.angle + direction
if self.angle < -2:  self.angle = -2
if self.angle >  2:  self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed

def move(self, speed):
self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20:  self.rect.centrex = 20
if self.rect.centerx > 620: self.rect.centerx = 620

class ObstacleClass (pygame.sprite.Sprite):
def __init__(self, image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False

def scroll(self, t_ptr):
self.rect.centery = self.location[1] - t_ptr

def create_map(start, end):
obstacles = pygame.sprite.Group()
gates = pygame.sprite.Group()
locations = []
for i in range(10):
row = random.randint(start, end)
col = random.randint (0, 9)
location  = [col * 64 + 20, row * 64 + 20]
if not  (location in locations):
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree" : img = "skier_tree.png"
elif type =="flag":  img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)
return obstacles

def animate() :
screen.fill([255, 255, 255])
pygame.display.update(obstacles.draw(screen))
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10, 10])
pygame.display.flip()

def updateObstacleGroup(map0, map1):
obstacles = pygame.sprite.Group()
for ob in map0:  obstacles.add(ob)
for ob in map1:  obstacles.add(ob)
return obstacles

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0

obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None,50)


while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT:
speed = skier.turn(1)
skier.move(speed)
map_position += speed[1]

if map_position >=640 and activeMap ==0:
activeMap = 1
map0 = create_map(20, 29)
obstacles = updateObstacleGroup(map0, map1)
if map_position >=1280 and activeMap == 1:
activeMap = 0
for ob in map0:
ob.location[1] = ob.location[1]  -  1280
map_position = map_position - 1280
map1 = create_map(10, 19)
obstacles = updateObstacleGroup(map0,map1)

for obstacle in obstacles:
obstacle.scroll(map_position)

hit = pygame.sprite.spritecollide(skier, obstacles, False)
if hit:
if hit [0]. type == "tree" and not hit[0].passed:
points = points - 100
skier.image = pygame.image.load("skier_crash.png")
animate()
pygame.time.delay(100

[Tutor] Beginner Programming Challenges

2011-11-20 Thread Bod Soutar
FOA: Any aspiring new programmers looking for some inspiration or projects.

There is a series of programming challenges being run on the ubuntu
forums
The challenges are aimed at beginners, and although they assume you are
running linux, this is not always a requirement.

The latest challenge can be found here:
http://ubuntuforums.org/showthread.php?t=1883907
An index of all the challenges is here:
http://ubuntuforums.org/showthread.php?t=1714324

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


Re: [Tutor] Help with error in ski game

2011-11-20 Thread bodsda
Just a guess but take a look at the spelling.

centerx
Or
centrex

Bodsda
Sent from my BlackBerry® wireless device

-Original Message-
From: Chloe Beck 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Sun, 20 Nov 2011 11:58:25 
To: 
Subject: [Tutor] Help with error in ski game

___
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] ProgressBar - Python and Powershell

2011-11-20 Thread Nikunj.Badjatya
Can anyone throw some light on this please. ! ?


From: tutor-bounces+nikunj.badjatya=emc@python.org 
[mailto:tutor-bounces+nikunj.badjatya=emc@python.org] On Behalf Of 
nikunj.badja...@emc.com
Sent: Thursday, November 17, 2011 4:21 PM
To: tutor@python.org
Subject: [Tutor] ProgressBar - Python and Powershell


Hi All,

I am using Python 2.7, windows Env.
I have an Installer written in Python(45%) and Powershell(55%) which is used to 
install Virtual Machines at specific locations. It is single threaded.
I am trying to implement a ProgressBar  for this installer. So that the user 
will come to know the progress of the installation.
I am using pypi progressbar module.
The top script is in python which inturns calls powershell scripts using 
subprocess.call() and proceeds with the installation.

I am taking a shared file between python and powershell, so that diff functions 
can update their %age completion level in to the file. Ex. Func1() updates it 
to 5%,  func2() will add its own 5% to it.. and so on.
At the start of the (main.py) script I am creating a thread whose sole purpose 
would be to keep "READ" a temp file for a new entry in it.
Based on this entry I can have my thread update the progressbar on the console.

My questions are:

1.   Can I have a better shared mechanism between python and powershell.?  
As I am using a file here. Reading + writing in python and writing only in 
powershell.  !

2.   Does this thread mechanism work.? I am yet to implement and test it.! 
:P What can be the possible shortfalls.?



Thanks

Nikunj
Bangalore - India

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


Re: [Tutor] ProgressBar - Python and Powershell

2011-11-20 Thread bodsda
This is just my opinion but I would have several (say 10) powershell scripts 
individually called by python, python will sit still until the powershell 
exits, then update the progress bar by 10% before calling the next script etc 
etc.

Bodsda 
Sent from my BlackBerry® wireless device

-Original Message-
From: 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Sun, 20 Nov 2011 08:00:43 
To: ; 
Subject: Re: [Tutor] ProgressBar - Python and Powershell

___
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] ProgressBar - Python and Powershell

2011-11-20 Thread Steven D'Aprano

nikunj.badja...@emc.com wrote:

Can anyone throw some light on this please. ! ?


This is a list for beginners learning Python. Your question is quite 
advanced for this list, as it involves both threads and subprocesses. It 
also uses a third-party module, progressbar, and a Windows-only 
application Powershell. You might get lucky and find somebody here that 
knows all of these technologies, but I think you're asking in the wrong 
place. Perhaps you should try in the main Python mailing list, 
python-l...@python.org, also available on Usenet as comp.lang.python.


By the way, you say that your application is single-threaded, but then 
describe using threads. That means it isn't single-threaded at all.


Good luck.



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


Re: [Tutor] Help with error in ski game

2011-11-20 Thread Steven D'Aprano

Chloe Beck wrote:


Traceback (most recent call last):
  File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 99, in 
skier.move(speed)
  File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 28, in move
if self.rect.centerx < 20:  self.rect.centrex = 20
AttributeError: 'pygame.Rect' object has no attribute 'centrex'


I'm not familiar with pygame, but my guesses are:

* you have used British spelling centre instead of American spelling 
center; try using centerx instead of centrex;


* if that fails, perhaps it should be spelled center.x

* if that fails, please open a Python interactive interpreter, and at 
the prompt enter:


import pygame
dir(pygame.Rect)

and show us the output.




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


[Tutor] Guess my number game

2011-11-20 Thread myles broomes
I asked for advice yesterday with some pseudocode for a 'guess my number' game 
I wrote up, and I was told to have a go at writing up the actual code. I've had 
a go but im struggling...

#guess my number games
#the user thinks of a number between 1 and 100,
#the computer then has to try and guess that number

#welcome the player to the game and explain the rules
print("\t\t\t Guess My Number")
input("Welcome player to the 'Guess My Number' game. Think of a number between 
1 and 100 and I will try to guess it. Press enter when you have thought of your 
number and are ready to begin.")

#import the random module
import random

#set initial values
tries = 1
attempt = random.randint(1,100)
guess = input("Is your number",attempt,"? (Enter 'yes' or 'no'.)")

#guessing loop
while guess == 'no':
tries += 1
incorrect = input("Was my guess too high or too low? (Type 'high' or 
'low'.) ")
if incorrect == 'high':
*
if incorrect == 'low':
*

#tell the player how many tries it took and end the game
print("Aha! I guessed it! And it only took",tries,"tries!")
input("Press enter to exit.")

Im having trouble trying to figure out a way to make the program guess 'higher' 
and 'lower' (Where the two asterisks are). Any help would be much appreciated! 
Oh and heres my pseudocode:

Welcome the user to the game
Explain the rules of the game
Wait for the user to think of a number
Once the user has thought of their number, take a guess
While the number has not been guessed correctly
Increase the number of 'tries' by 1
Ask the user if the guess was too high or too low
If the guess was too high
guess lower
If the guess was too low
guess higher
Once the number has been guessed correctly, tell the user the number of tries 
it took
Exit the game

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


[Tutor] Shortening code [was Re: Tutor Digest, Vol 93, Issue 117]

2011-11-20 Thread Alan Gauld


Please change to a sensible subject when replying to digest messages.

On 20/11/11 11:45, Mic wrote:
> I have done my best to make the code more readable now.
> Here is the result.


from tkinter import*

button1_color="green"
button1_value=False

button2_color="green"
button2_value=False


buttonX_value still doesn't say much about *why* the variable is there. 
What are you storing in it. What does the value represent?


Also, do you really need the colors, you don't actually use them for 
anything below except the initial color, but you might as well just hard 
code it to "green", it would be shorter and more explicit...


##
class Window(Frame):
   def __init__(self,master):...

   def create_widgets(self):

   #Creates hello button1
   self.hello_bttn1=Button(self,bg=button1_color,
   text="Hi_1", command=self.button1_clicked)
   self.hello_bttn1.grid()

   #Creates hello button2
   self.hello_bttn2=Button(self,bg=button2_color,
   text="Hi_1", command=self.button2_clicked)
   self.hello_bttn2.grid()

   def button1_clicked(self):
   """ This method runs if button one is clicked"""

   def change_button1_value():
   global button1_value
   button1_value=not button1_value

   change_button1_value()


>if button1_value:
>self.hello_bttn1.configure(bg="red", text="Hi_2")

Note that this is the line that really changes the button's color.
And it does not use the variable...

>   def change_button1_color_red():
>   global button1_color
>   button1_color=("red")
>   change_button1_color_red()

Whereas this function and its call do nothing but change the value of a 
variable that is never used after the initial creation. If you took this 
out the code would run with exactly the same effect.


>   else:
>   self.hello_bttn1.configure(bg="green", text="Hi_1")

Same, here. You set the color explicitly, then create
a function and call it just to update a variable you don't use.

>   def change_button1_color_green():
>   global button1_color
>   button1_color=("green")
>   change_button1_color_green()


###
   def button2_clicked(self):
   """This method runs if button two is clicked"""

   def change_button2_value():
   global button2_value
   button2_value=not button2_value

   change_button2_value()

   if button2_value:

   self.hello_bttn2.configure(bg="red", text="Hi_2")

   def change_button2_color_red():
   global button2_color
   button2_color=("red")
   change_button2_color_red()

   else:
   self.hello_bttn2.configure(text="Hi_1", bg="green")

   def change_button2_color_green():
   global button2_color
   button2_color=("green")
   change_button2_color_green()



Notice that both button handlers are identical except they work on 
different buttons and test values. What we'd like is a single

function that gets passed the widget and test as parameters.
It would look like this:

def button_clicked(self, widget, test):
if test:
widget.configure(bg="red", text="Hi_2")
else:
widget.configure(text="Hi_1", bg="green")


and to call it we create two short event handlers:

def button1_clicked(self):
 self.button1_value = not self.button1_value
 self.button_clicked(button1,self.button1_value)


def button2_clicked(self):
 self.button2_value = not self.button2_value
 self.button_clicked(button2,self.button2_value)


Notice I've moved the test values to instance variables
rather than globals, but thats just a style thing you could have 
referenced the globals within the handlers instead.


I also removed those spurious functions from the main
button_clicked code.


> However, I did not understand this part of your suggestions:

> > Generally you build a data table with all the config parameters that
> > will varty then you build a loop to read the values from the
> > data table.
> > Store the created buttons in a list or dictionary.
>
> I must admit that I have never heard of a "data table" before.
> Is this easy to do, for a beginner like me?


Yes its just a list of tuples/lists. For your two buttons uit would look 
like:


#  buttonName text, color, command
self.button_params = [
("b1", "Hi_1", "green", self.button1_clicked),
("b2", "Hi_2", "green", self.button2_clicked)
]

Now your create_widgets looks like:

   def create_widgets(self):
   self.Buttons = {}
   for params in self.button_params:
   b = Button(self, bg=params[1],
  text=params[2], command=params[3])
   self.Buttons[params[0]] = b


And now

Re: [Tutor] Guess my number game

2011-11-20 Thread Alan Gauld

On 20/11/11 15:29, myles broomes wrote:
> ...I was told to have a go at writing up the actual code.

Well done, thats a good start.


#guess my number games
#the user thinks of a number between 1 and 100,
#the computer then has to try and guess that number

#welcome the player to the game and explain the rules
print("\t\t\t Guess My Number")
input("Welcome player to the 'Guess My Number' game. Think of a number between 1 and 
100 and I will try to guess it. Press enter when you have thought of your number and are 
ready to begin.")


First thing is that you need to store the number that the user typed.
So you need a variable - lets call it userNumber - and an assignment. 
While we are at it lets convert the string version the user gave us to a 
number:


userNumber = int( input() )



#import the random module
import random


The comment is redundant since the code is obvious. Use comments to tell 
us *why* you are doing things not to tell us what you are doing - we can 
all read the code...


Its also conventional practice to put all imports at the top of the 
program. Its not necessary, but it saves people hunting for the imports 
if they are all together at the top.



#set initial values
tries = 1
attempt = random.randint(1,100)
guess = input("Is your number",attempt,"? (Enter 'yes' or 'no'.)")


The name guess is a bit misleading since its really the users response,
The Guess is actually what you have already named attempt.
Good naming makes a big difference to the readability of your code so 
it's worth really thinking about what the variables are doing and 
choosing descriptive names. Also the names should follow the function

of the variables, not their type.


#guessing loop
while guess == 'no':
tries += 1
incorrect = input("Was my guess too high or too low? (Type 'high' or 'low'.) 
")
if incorrect == 'high':
*


Here you want to generate a new value for attempt but insterad of using 
1-100 you want it between 1-(attempt-1)




if incorrect == 'low':


Here you want to generate a new value for attempt but instead of using 
1-100 you want it between (attempt+1) - 100


And you already know how to set attempt to a number between two values...

Then before you go back to the top of the loop you need to ask the user 
if the new attempt is ok and store that in guess.


Have a go at writing that...


#tell the player how many tries it took and end the game
print("Aha! I guessed it! And it only took",tries,"tries!")
input("Press enter to exit.")


And that bit is fine. :-)

HTH
--
Alan G
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] ProgressBar - Python and Powershell

2011-11-20 Thread Nikunj.Badjatya
Thanks for the reply Steve.
I mean, the installer as a sole is single threaded.
They way to implement progressbar may turn it to multithreaded.

Anyways, I have posted the problem in pyhton-list ml.

Thanks
Nikunj

-Original Message-
From: tutor-bounces+nikunj.badjatya=emc@python.org 
[mailto:tutor-bounces+nikunj.badjatya=emc@python.org] On Behalf Of Steven 
D'Aprano
Sent: Sunday, November 20, 2011 8:46 PM
To: tutor@python.org
Subject: Re: [Tutor] ProgressBar - Python and Powershell

nikunj.badja...@emc.com wrote:
> Can anyone throw some light on this please. ! ?

This is a list for beginners learning Python. Your question is quite 
advanced for this list, as it involves both threads and subprocesses. It 
also uses a third-party module, progressbar, and a Windows-only 
application Powershell. You might get lucky and find somebody here that 
knows all of these technologies, but I think you're asking in the wrong 
place. Perhaps you should try in the main Python mailing list, 
python-l...@python.org, also available on Usenet as comp.lang.python.

By the way, you say that your application is single-threaded, but then 
describe using threads. That means it isn't single-threaded at all.

Good luck.



-- 
Steven
___
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] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread dave selby
Hi All,

I have a long string which is an HTML file, I strip the HTML tags away
and make a list with

text = re.split('<.*?>', HTML)

I then tried to search for a string with text.index(...) but it was
not found, printing HTML to a terminal I get what I expect, a block of
tags and text, I split the HTML and print text and I get loads of

\x00T\x00r\x00i\x00a\x00  ie I get \x00 breaking up every character.

Any idea what is happening and how to get back to a list of ascii strings ?

Cheers

Dave

-- 

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread Steve Willoughby
Where did the string come from?  It looks at first glance like you have two 
bytes for each character instead of the one you expect.  Is this perhaps a 
Unicode string instead of ASCII?

Sent from my iPad

On 2011/11/20, at 10:28, dave selby  wrote:

> Hi All,
> 
> I have a long string which is an HTML file, I strip the HTML tags away
> and make a list with
> 
> text = re.split('<.*?>', HTML)
> 
> I then tried to search for a string with text.index(...) but it was
> not found, printing HTML to a terminal I get what I expect, a block of
> tags and text, I split the HTML and print text and I get loads of
> 
> \x00T\x00r\x00i\x00a\x00  ie I get \x00 breaking up every character.
> 
> Any idea what is happening and how to get back to a list of ascii strings ?
> 
> Cheers
> 
> Dave
> 
> -- 
> 
> Please avoid sending me Word or PowerPoint attachments.
> See http://www.gnu.org/philosophy/no-word-attachments.html
> ___
> 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] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread Sarma Tangirala
Would the html parser library in python be a better idea as opposed to
using split? That way you have greater control over what is in the html.
On 20 Nov 2011 23:58, "dave selby"  wrote:

> Hi All,
>
> I have a long string which is an HTML file, I strip the HTML tags away
> and make a list with
>
> text = re.split('<.*?>', HTML)
>
> I then tried to search for a string with text.index(...) but it was
> not found, printing HTML to a terminal I get what I expect, a block of
> tags and text, I split the HTML and print text and I get loads of
>
> \x00T\x00r\x00i\x00a\x00  ie I get \x00 breaking up every character.
>
> Any idea what is happening and how to get back to a list of ascii strings ?
>
> Cheers
>
> Dave
>
> --
>
> Please avoid sending me Word or PowerPoint attachments.
> See http://www.gnu.org/philosophy/no-word-attachments.html
> ___
> 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] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread Steve Willoughby

On 20-Nov-11 12:04, Sarma Tangirala wrote:

Would the html parser library in python be a better idea as opposed to
using split? That way you have greater control over what is in the html.


Absolutely. And it would handle improper HTML (like unmatched brackets) 
gracefully where the split will just do the wrong thing.




On 20 Nov 2011 23:58, "dave selby" mailto:dave6...@gmail.com>> wrote:

Hi All,

I have a long string which is an HTML file, I strip the HTML tags away
and make a list with

text = re.split('<.*?>', HTML)

I then tried to search for a string with text.index(...) but it was
not found, printing HTML to a terminal I get what I expect, a block of
tags and text, I split the HTML and print text and I get loads of

\x00T\x00r\x00i\x00a\x00  ie I get \x00 breaking up every character.

Any idea what is happening and how to get back to a list of ascii
strings ?

Cheers

Dave

--

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
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



--
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] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread Steve Willoughby
It's customary to copy the list with answers, so everyone can benefit 
who may run into the same issue, too.


On 20-Nov-11 11:38, dave selby wrote:

It came from some automated HTML generation app ... I just had the
idea of looking at in with ghex  every other character is \00
, thats mad. OK will try ans replace('\00', '') in the string
before splitting


Those bytes are there for a reason, it's not mad.  It's using wide 
characters, possibly due to Unicode encoding.  If there are special
characters involved (multinational applications or whatever), you'll 
destroy them by killing the null bytes and won't handle the case of that 
high-order byte being something other than zero.


Check out Python's Unicode handling, and character set encode/decode 
features for a robust way to translate the output you're getting.





Cheers

Dave

On 20 November 2011 19:15, Steve Willoughby  wrote:

Where did the string come from?  It looks at first glance like you have two 
bytes for each character instead of the one you expect.  Is this perhaps a 
Unicode string instead of ASCII?

Sent from my iPad

On 2011/11/20, at 10:28, dave selby  wrote:


Hi All,

I have a long string which is an HTML file, I strip the HTML tags away
and make a list with

text = re.split('<.*?>', HTML)

I then tried to search for a string with text.index(...) but it was
not found, printing HTML to a terminal I get what I expect, a block of
tags and text, I split the HTML and print text and I get loads of

\x00T\x00r\x00i\x00a\x00  ie I get \x00 breaking up every character.

Any idea what is happening and how to get back to a list of ascii strings ?

Cheers

Dave

--

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor









--
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] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread Steven D'Aprano

dave selby wrote:


I split the HTML and print text and I get loads of

\x00T\x00r\x00i\x00a\x00  ie I get \x00 breaking up every character.

Any idea what is happening and how to get back to a list of ascii strings ?



How did you generate the HTML file? What other applications have you 
used to save the document?


Something in the tool chain before it reached Python has saved it using 
a wide (four byte) encoding, most likely UTF-16 as that is widely used 
by Windows and Java. With the right settings, it could take as little as 
opening the file in Notepad, then clicking Save.


If this isn't making sense to you, you should read this:

http://www.joelonsoftware.com/articles/Unicode.html

If my guess is right that the file is UTF-16, then you can "fix" it by 
doing this:



# Untested.
f = open("my_html_file.html", "r")
text = f.read().decode("utf-16")  # convert bytes to text
f.close()
bytes = text.encode("ascii")  # If this fails, try "latin-1" instead
f = open("my_html_file2.html", "w")  # write bytes back to disk
f.write(bytes)
f.close()

Once you've inspected the re-written file my_html_file2.html and it is 
okay to your satisfaction, you can delete the original one.



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


Re: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ?

2011-11-20 Thread Dave Angel

On 11/20/2011 04:45 PM, Steven D'Aprano wrote:



Something in the tool chain before it reached Python has saved it 
using a wide (four byte) encoding, most likely UTF-16 as that is 
widely used by Windows and Java. With the right settings, it could 
take as little as opening the file in Notepad, then clicking Save.




UTF-16 is a two byte format.  That's typically what Windows uses for 
Unicode.  It's Unices that are more likely to use a four-byte format.


--

DaveA

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


[Tutor] Is there a way to add paths in Eric?

2011-11-20 Thread Mark Lybrand
I am using Windows Vista.  I have some python scripts I have been
developing in my learning folder.  Can I add the path to the folder in eric
to call them interactively, or will I need to move them?



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


Re: [Tutor] Is there a way to add paths in Eric?

2011-11-20 Thread Mark Lybrand
Okay, I have answered my own question

import sys
sys.append()

Sorry for bothering.

Mark

On Sun, Nov 20, 2011 at 6:21 PM, Mark Lybrand  wrote:

> I am using Windows Vista.  I have some python scripts I have been
> developing in my learning folder.  Can I add the path to the folder in eric
> to call them interactively, or will I need to move them?
>
>
>
> --
> Mark :)
>



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


[Tutor] How to get module name from ImportError

2011-11-20 Thread Nikunj.Badjatya
Hi All,

Please look at the following snippet.
{{{

# User defined modules
try:
from scripts import precheck
from scripts import validate
from scripts import constants
except ImportError:
print("ERROR: One of the modules (..scripts/precheck.py, validate.py, 
constants) is not present.")
print("INFO : Please verify the above modules, and restart the 
installation")
sys.exit(1)

}}}

See the red line.
I want to get the name of the particular module which is not available and 
hence causing ImportError.
One of the ways can be to get the STDERR and process it using re. !?

Is there a better alternate available .?

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


Re: [Tutor] How to get module name from ImportError

2011-11-20 Thread Christian Witts

On 2011/11/21 07:54 AM, nikunj.badja...@emc.com wrote:


Hi All,

Please look at the following snippet.

{{{

# User defined modules

try:

from scripts import precheck

from scripts import validate

from scripts import constants

except ImportError:

print("ERROR: One of the modules (..scripts/precheck.py, 
validate.py, constants) is not present.")


print("INFO : Please verify the above modules, and restart the 
installation")


sys.exit(1)

}}}

See the red line.
I want to get the name of the particular module which is not available 
and hence causing ImportError.


One of the ways can be to get the STDERR and process it using re. !?

Is there a better alternate available .?

Thanks

Nikunj



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

>>> try:
... import nothing
... except ImportError, err_msg:
... print err_msg
...
No module named nothing

Hope that helps.
--

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


Re: [Tutor] How to get module name from ImportError

2011-11-20 Thread Nikunj.Badjatya
Exactly !
Thanks a lot.

From: Christian Witts [mailto:cwi...@compuscan.co.za]
Sent: Monday, November 21, 2011 11:36 AM
To: Badjatya, Nikunj
Cc: tutor@python.org
Subject: Re: [Tutor] How to get module name from ImportError

On 2011/11/21 07:54 AM, nikunj.badja...@emc.com 
wrote:
Hi All,

Please look at the following snippet.
{{{

# User defined modules
try:
from scripts import precheck
from scripts import validate
from scripts import constants
except ImportError:
print("ERROR: One of the modules (..scripts/precheck.py, validate.py, 
constants) is not present.")
print("INFO : Please verify the above modules, and restart the 
installation")
sys.exit(1)

}}}

See the red line.
I want to get the name of the particular module which is not available and 
hence causing ImportError.
One of the ways can be to get the STDERR and process it using re. !?

Is there a better alternate available .?

Thanks
Nikunj




___

Tutor maillist  -  Tutor@python.org

To unsubscribe or change subscription options:

http://mail.python.org/mailman/listinfo/tutor
>>> try:
... import nothing
... except ImportError, err_msg:
... print err_msg
...
No module named nothing

Hope that helps.
--

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


Re: [Tutor] How to get module name from ImportError

2011-11-20 Thread Dave Angel

On 11/21/2011 01:23 AM, nikunj.badja...@emc.com wrote:

Exactly !
Thanks a lot.
1)
You really shouldn't top-post.  Nor should you try to indicate something 
with color, since this is a text-based forum.


I would suggest that you do not try to parse error messages.  (If you're 
going to just print the message and exit, then there's no advantage in 
catching it.)  Instead, arrange the answer to be given to you directly.  
Two ways come to mind:


1) use separate try/catch blocks
2) use variables to indicate how far you got before the exception happened.

I think I would just start with

precheck = validate= constants = None

then after the exception is reported, you can check each of these with 
something like:


if constants:

One more thing.  You appear to be  using Python 3.  So the correct 
syntax for the except is:


 except ImportError as  error_obj:

Note that the value is *not* a string, but is an object of some subclass 
of ImportError.





From: Christian Witts [mailto:cwi...@compuscan.co.za]
Sent: Monday, November 21, 2011 11:36 AM
To: Badjatya, Nikunj
Cc: tutor@python.org
Subject: Re: [Tutor] How to get module name from ImportError

On 2011/11/21 07:54 AM, nikunj.badja...@emc.com 
 wrote:
Hi All,

Please look at the following snippet.
{{{

# User defined modules
try:
 from scripts import precheck
 from scripts import validate
 from scripts import constants
except ImportError:
 print("ERROR: One of the modules (..scripts/precheck.py, validate.py, 
constants) is not present.")
 print("INFO : Please verify the above modules, and restart the 
installation")
 sys.exit(1)

}}}

See the red line.
I want to get the name of the particular module which is not available and 
hence causing ImportError.
One of the ways can be to get the STDERR and process it using re. !?

Is there a better alternate available .?

Thanks
Nikunj




___

Tutor maillist  -  Tutor@python.org

To unsubscribe or change subscription options:

http://mail.python.org/mailman/listinfo/tutor

try:

... import nothing
... except ImportError, err_msg:
... print err_msg
...
No module named nothing

Hope that helps.
--

Christian Witts
Python Developer



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



--

DaveA

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