bumsfeld 413 Nearly a Posting Virtuoso

Python also has HTMLParser module that can help you muchly:

# extract a specified text from web page HTML source code

import urllib2
import HTMLParser
import cStringIO   # acts like file in memory

class HTML2Text(HTMLParser.HTMLParser):
    """
    extract text from HTML code basically using inherited
    class HTMLParser and some additional custom methods
    """
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.output = cStringIO.StringIO()

    def get_text(self):
        """get the text output"""
        return self.output.getvalue()

    def handle_starttag(self, tag, attrs):
        """handle <br> tags"""
        if tag == 'br':
            # need to put one new line in
            self.output.write('\n')

    def handle_data(self, data):
        """normal text"""
        self.output.write(data)

    def handle_endtag(self, tag):
        if tag == 'p':
            # end of paragraph add newline
            self.output.write('\n')


def extract(html, sub1, sub2):
    """
    extract string from text between first
    occurances of substrings sub1 and sub2
    """
    return html.split(sub1, 1)[-1].split(sub2, 1)[0]


# you may need to update this web page for your needs
url = 'http://www.bom.gov.au/products/IDN10060.shtml#HUN'

# get the raw HTML code
try:
    file_handle = urllib2.urlopen(url)
    html1 = file_handle.read()
    file_handle.close()
    print '-'*70
    print 'Data from URL =', url
except IOError:
    print 'Cannot open URL %s for reading' % url
    html1 = 'error!'
  
#print '-'*70; print html1  # testing

# extract code between sub1 and sub2
# you may need to update sub1 and sub2 for your needs
sub1 = 'www.bom.gov.au/weather/nsw</a></P><P>'
sub2 = 'The next routine forecast'
html2 = extract(html1, sub1, sub2)

#print '-'*70; print html2  # testing

# remove HTML tags to give clean text
p = HTML2Text()
p.feed(html2)
text = p.get_text()
print '-'*70
print text
print '-'*70

You can …

bumsfeld 413 Nearly a Posting Virtuoso

HI
I was having a look into classes and i noticed i saw a lot of things like

class fruitcake(object):
    pass

my question is what is the point of the "object" being in the class arguments as it is a Built In Function and i couldn't work out what putting it there did

Class object is the base class that is at the top of any inheritance tree. It designates the new style Python class (Python24 and higher) having some additional feautures like __slots__ which prevents new variable creation outside the class. __slots__ also replaces the usual __dict__ in the class to give speed improvement.

To show it's methods use:

print dir(object)

Also, do not use 'object' for variable name.

bumsfeld 413 Nearly a Posting Virtuoso

Anyone know good drug that fights senility? One of the presidential candidates is interested in cutting back his senior moments.

bumsfeld 413 Nearly a Posting Virtuoso

Some editors like DrPython, UliPad, PyScripter, IDLE have internal output window that will stay open without the use of console wait line like raw_input("Press <Enter> to exit.")

bumsfeld 413 Nearly a Posting Virtuoso

Writing your print statement to file:

# open/create text file for writing in main()
fout = open( "test1.txt", "w" )  # may need "a" for append

# in your program under this line
# print '\tn: %d, sort time: %f' % (n, dt)
# add this line
print >>fout, '\tn: %d, sort time: %f' % (n, dt)

# you may have to make 'fout' global or better pass 
# it to your function as argument
bumsfeld 413 Nearly a Posting Virtuoso

You can also use Python's module profile:

import profile

def get_primes3(n):
    if n < 2:  return []
    if n == 2: return [2]
    nums = range(3, n, 2)
    idx = 0
    while idx <= (n - 1)**0.5 - 2:
        for j in xrange( idx + nums[idx], n//2 - 1, nums[idx] ):
            # replace nonprime with zero (False)
            nums[j] = 0
        idx += 1
        while idx < n - 2:
            if nums[idx] != 0:
                break
            idx += 1
    # remove all zero items
    return [2] + [x for x in nums if x != 0]

profile.run('get_primes3(15000)')

"""
result of profile.run

         5 function calls in 0.004 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(range)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.003    0.003    0.004    0.004 <module3>:3(get_primes3)
        1    0.000    0.000    0.004    0.004 <string>:1(?)
        1    0.000    0.000    0.004    0.004 profile:0(get_primes3(15000))
        0    0.000             0.000          profile:0(profiler)
"""
bumsfeld 413 Nearly a Posting Virtuoso

Ubuntu seems to be one ugly beast, I have heard other poeple complain about it, particularly Python programmers.

bumsfeld 413 Nearly a Posting Virtuoso

historically it was the other way around as loads of wemen died in childbirth

On the other hand, lots of young men died as they were sent off to war.

bumsfeld 413 Nearly a Posting Virtuoso

Running out of integer space in series of scientific calculations in C. The results get really goofy at times without any warning, depending on the data input.

bumsfeld 413 Nearly a Posting Virtuoso

Your program reads in all the lines into one list of lines and then even makes one copy of this rather large list. The code below reads in the lines as needed for processing:

...

for vhstring in file(vhdat):
    # remove trailing whitespace
    vhstring = vhstring.rstrip()
    # your processing starts here ...
    NPANXX = vhstring[:6]             # NPA
    NXXType = vhstring[16:18]
    ...
bumsfeld 413 Nearly a Posting Virtuoso

Everything comes to an end, nothing gloomy about it. 2012, I don't know, could be earlier or could be later. Let's celebrate that it didn't come earlier, and from 2012 on celebrate that it will come later.

bumsfeld 413 Nearly a Posting Virtuoso

You are trying to concatinate class instance with string ".ac" that will not work. Why don't you simply create the new class attribute dynamically this way and then you can use it.

searchSpace[0].ac = None
bumsfeld 413 Nearly a Posting Virtuoso

When you run the above file, carefully read the messages. PIL has history of giving problems with py2exe. Just for testing, use small PIL program with py2exe.

Of course, I am using Windows Vista and expect all sorts of problems anyway!

bumsfeld 413 Nearly a Posting Virtuoso
bumsfeld 413 Nearly a Posting Virtuoso

... Java can be compiled into bytecode and run onto of a virtual machine, But since python is interprated, it cannot.
...

Utter bull! Python is also compiled to bytecode and then run onto virtual machine. Please educate yourself a little before you say ignorant things.

Have you actually read this post in this thread?
http://www.daniweb.com/forums/post575389-40.html

bumsfeld 413 Nearly a Posting Virtuoso

Compared to Java, Python has simplified a lot of the syntax. It will spoil you, and you may actually have fun.

bumsfeld 413 Nearly a Posting Virtuoso

You might want to play with the Python builtin module filecmp:

# compare two files and check if they are equal
# files can be binary or text based

import filecmp

# pick two files you want to compare ...
file1 = "Boing1.wav"
file2 = "Boing2.wav"

if filecmp.cmp(file1, file2):
    print "Files %s and %s are identical" % (file1, file2)
else:
    print "Files %s and %s differ!" % (file1, file2)
bumsfeld 413 Nearly a Posting Virtuoso

thanks for all the help everyone! it really helped me. im still a noob when it comes to programming, espically to python. its just to bad that after this quarter i wont be working with python anymore. its all java and c++ lol.

Hehe, every computer student has to go through the pain of C++ or Java programming, so you learn to be humble in the eyes of your trainer. In science, it is more important to solve the problems quickly, so Python rules.

bumsfeld 413 Nearly a Posting Virtuoso

You can do it with label and use spaces of the desired background colour. Here is example:

# Tkinter progress bar experiment
# using label and string of spaces

import Tkinter as tk

root = tk.Tk()
# width 300 and height 100, no offsets
root.geometry("300x100+0+0")

space = " "
s = ""
label = tk.Label(root, text=s, bg='blue')
label.pack(anchor='nw')

for k in range(80):
    s += space
    # increments every 100 milliseconds
    label.after(100,label.config(text=s))
    label.update()  # needed

root.mainloop()
vegaseat commented: nice and polite +7
bumsfeld 413 Nearly a Posting Virtuoso

Also, if you work with wxPython Gui Toolkit you need to use False in this line:
app = wx.App(False)
This way the error actually shows up in the cmd window or editor's designated display window.

The default is True and the error shows up (flickers up) in small window created by wxPython.

bumsfeld 413 Nearly a Posting Virtuoso

Use something like the DrPython IDE, that one has its own output window. Also editors like ConText have option that allow you to keep the cmd window open.

bumsfeld 413 Nearly a Posting Virtuoso

Jeff's suggestion is modern Python. Make sure that your number is iterated as string:

squaredigits = lambda x: sum([int(i)*int(i) for i in str(x)])

print squaredigits(442)  # -->  36

Note: filter(), map() and reduce() will go away with Python30

# add this to future code
try: filter and map and reduce
except:
    def filter(f, s): return [x for x in s if f(s)]
    def map(f, *s): return [f(*x) for x in zip(*s)]
    def reduce(f, s, i=None):
        r = i
        for x in s:
            r = f(r, x)
        return r

Part of the reason is that list comprehensions are simply so much faster than using defined function call. Also reduce() isn't used much. Good news is that lambda will stay.

bumsfeld 413 Nearly a Posting Virtuoso

My hometown is loaded with Italian restaurants, I am surprised no one has voted Italy yet!

Most of those treaded frozen TV dinners are some kind of Italian fare. Quite a turn-off!

bumsfeld 413 Nearly a Posting Virtuoso

Is oxo the same as tic-tac-toe?

bumsfeld 413 Nearly a Posting Virtuoso

Vegaseat left this example of the difflib module somewhere in the code snippets:

# find the difference between two texts
# tested with Python24   vegaseat  6/2/2005

import difflib

text1 = """The World's Shortest Books:
Human Rights Advances in China
"My Plan to Find the Real Killers" by OJ Simpson
"Strom Thurmond:  Intelligent Quotes"
America's Most Popular Lawyers
Career Opportunities for History Majors
Different Ways to Spell "Bob"
Dr. Kevorkian's Collection of Motivational Speeches
Spotted Owl Recipes by the EPA
The Engineer's Guide to Fashion
Ralph Nader's List of Pleasures
"""

text2 = """The World's Shortest Books:
Human Rights Advances in China
"My Plan to Find the Real Killers" by OJ Simpson
"Strom Thurmond:  Intelligent Quotes"
America's Most Popular Lawyers
Career Opportunities for History Majors
Different Ways to Sell "Bob"
Dr. Kevorkian's Collection of Motivational Speeches
Spotted Owl Recipes by the EPA
The Engineer's Guide to Passion
Ralph Nader's List of Pleasures
"""

# create a list of lines in text1
text1Lines = text1.splitlines(1)
print "Lines of text1:"
for line in text1Lines:
  print line,

print

# dito for text2
text2Lines = text2.splitlines(1)
print "Lines of text2:"
for line in text2Lines:
  print line,

print  

diffInstance = difflib.Differ()
diffList = list(diffInstance.compare(text1Lines, text2Lines))

print '-'*50
print "Lines different in text1 from text2:"
for line in diffList:
  if line[0] == '-':
    print line,
bumsfeld 413 Nearly a Posting Virtuoso

I don't think that a stupid filter will ever work. The stupid folks are just too smart for that.

bumsfeld 413 Nearly a Posting Virtuoso

Their album could have been top seller, if they would have called it "2012" (2 birds with one shot!).

bumsfeld 413 Nearly a Posting Virtuoso

Could be ultra-high energy cosmic rays, sub-atomic matter that breaks free just before stars are gobbled up by the gravitational pull of black holes. A finding published in the journal Science by Alexander Kusenko, a professor of physics and astronomy at the University of California, Los Angeles. He worked on the study with physicists and astronomers from 17 countries.

bumsfeld 413 Nearly a Posting Virtuoso

I still think it's the Antichrist that causes the end of the world as we know it! Remember, the Antichrist could be female.

bumsfeld 413 Nearly a Posting Virtuoso

I can't tell if that is sarcasm or not, because you write so terribly.

Dear Mister Freedom Toast: "Written well enough for even stupid folks to discover sarcasm."

bumsfeld 413 Nearly a Posting Virtuoso

I think we are missing the invasion by a outerspace intelligence that by poor choice lands in Washington DC, and consequently looks at us as just one pest to be exterminated.

bumsfeld 413 Nearly a Posting Virtuoso
bumsfeld 413 Nearly a Posting Virtuoso

Exciting world we have! One always learns something new!

bumsfeld 413 Nearly a Posting Virtuoso

Python is portable across a large umber of Operating Systems, so when you use OS calls, the error returned is specific for the particular OS used and generated by that OS. It would be tough for the developers of Python to cross reference all these different error numbers.

bumsfeld 413 Nearly a Posting Virtuoso

Jeff,
if you want to know how he did it, just click temporarily on "REPLY W/QUOTE" and look at the text shown.

bumsfeld 413 Nearly a Posting Virtuoso

If you want to do that sort of thing, you might as well download the console module from:
http://effbot.org/downloads/

Console interface for Windows only (versions up to Python25 available):
console-1.1a1-20011229.win32-py2.5.exe

Look at documentation at:
http://effbot.org/zone/console-handbook.htm

bumsfeld 413 Nearly a Posting Virtuoso

15 minutes into testing the new Boa Constructor (boa-constructor-0.6.1.bin.setup.exe), very impressed with it.

It does have ctrl/space for code completion choices!

bumsfeld 413 Nearly a Posting Virtuoso

Sorry, I have not used Boa Constructor for a while. It seems like they have had major recent upgrade at:
http://sourceforge.net/project/downloading.php?group_id=1909&use_mirror=osdn&filename=boa-constructor-0.6.1.bin.setup.exe&74856058

That one installs well and works with Python25 and wxPython28, even on a Vista machine. I am testing it out now.

bumsfeld 413 Nearly a Posting Virtuoso
bumsfeld 413 Nearly a Posting Virtuoso

You can type in the SPE Python shell
help('Tkinter')

from Tkinter import *

root = Tk()

root.

Actually an IDE called PyScripter has this feature. The moment you type the dot a dropdown list of possible choices appears.

bumsfeld 413 Nearly a Posting Virtuoso

Which version of wxPython do you have installed?
I am having the same problem on my newest computer.

bumsfeld 413 Nearly a Posting Virtuoso

The frame builder wxGlade comes with Stani's Python Editor (SPE). You can still get a free download of SPE 0.8.3c, the Python IDE for Movable Python at:
http://www.tradebit.com/filedetail.php/839343
Downloads as spe-0.8.3c.zip, and should work with Python 2.3 - 2.5. Simply extract the '_spe' directory into your Python 'lib' folder. You can then run 'spe.pyw' from there. Again, you need the wxPython GUI toolkit installed first for SPE to work!

bumsfeld 413 Nearly a Posting Virtuoso

There is Boa Constructor (similar to Delphi) that uses wxPython as the GUI toolkit (you need wxPython isstalled first), free download from:
http://downloads.sourceforge.net/boa-constructor/boa-constructor-0.4.4.win32.exe

There is also wxGlade, just frame builder/designer, also using wxPython:
http://wxglade.sourceforge.net/

bumsfeld 413 Nearly a Posting Virtuoso

My advice, use the vector container. One of the advantages of using C++.

bumsfeld 413 Nearly a Posting Virtuoso

This might help:

import wx


class DemoFrame(wx.Frame):
    
    def __init__(self, parent, id):
        
        wx.Frame.__init__(self, parent, id, 'Demo', size=(600, 400), pos=(300,300))
        
        # make the widgets ...
        self.panel1=wx.Panel (self, -1)
        self.panel1.SetBackgroundColour ("white")

        # create splitter windows
        self.splitter = wx.SplitterWindow(self,
            style=wx.CLIP_CHILDREN | wx.SP_LIVE_UPDATE | wx.SP_3D)
        self.splitter2 = wx.SplitterWindow(self.splitter, -1,
            style=wx.CLIP_CHILDREN | wx.SP_LIVE_UPDATE | wx.SP_3D)
        self.mainpanel = wx.Panel(self.splitter, -1)
        self.leftpanel2 = wx.Panel(self.splitter2, -1, style=wx.WANTS_CHARS)
        self.mainpanel.SetBackgroundColour ("white")
        self.splitter2.SetBackgroundColour (wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))

        # create tree control
        self.tree = wx.TreeCtrl(self.mainpanel, -1, wx.Point(0, 0), wx.Size(160, 250),
            wx.TR_DEFAULT_STYLE | wx.NO_BORDER)
        self.root = self.tree.AddRoot("Root Demo Item")
        item1 = self.tree.AppendItem (self.root, "Item1",0)
        item2 = self.tree.AppendItem (self.root, "Item2",0)
        self.tree.Expand(self.root)

        # add other widgets
        self.help = wx.TextCtrl(self.splitter2, -1,
            style = wx.TE_MULTILINE|wx.TE_READONLY | wx.HSCROLL)
        self.staticboxstyles = wx.StaticBox(self.leftpanel2, -1, "Demo", size=(485, 240))
        
        self.DoLayout ()
        
        # bind tree action
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)

    
    def DoLayout (self):
        
        # sizers
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panelsizer = wx.BoxSizer(wx.VERTICAL)
        sizer1 = wx.BoxSizer(wx.VERTICAL)
        sizer2 = wx.BoxSizer(wx.VERTICAL)
      
        # add widgets to sizers
        panelsizer.Add(self.splitter, 1, wx.EXPAND, 0)
        sizer1.Add(self.tree, 1, wx.EXPAND)
        sizer2.Add(self.staticboxstyles, 1, wx.BOTTOM|wx.EXPAND|wx.ALIGN_BOTTOM, 60 )
    
        # set sizers
        self.mainpanel.SetSizer(sizer1)
        self.leftpanel2.SetSizer(sizer2)
        self.SetSizer(panelsizer)
        mainsizer.Layout()
        self.Layout()

        # set splitters
        self.splitter.SplitVertically(self.mainpanel, self.splitter2, 300)
        self.splitter2.SplitHorizontally(self.leftpanel2, self.help, -160)
        self.splitter.SetSashPosition (200)


    def OnSelChanged(self, event):
        self.item = event.GetItem()
        select = self.tree.GetItemText(self.item)
        if self.item:
            # test (create your help string here)
            str1 = "Selected item = %s\n" % select
            self.help.SetValue(str1)
        if select == 'Item1':
            # test (create your check boxes instead)
            self.staticbox_check = wx.StaticBox(self.leftpanel2, -1, "Check",
                pos=(10, 20), size=(300, 100))
        if select == 'Item2':
            # test (create your radio buttons instead)
            self.staticbox_check = wx.StaticBox(self.leftpanel2, -1, "Radio",
                pos=(10, 20), size=(300, 100))
        

if __name__ == '__main__':
    app = wx.PySimpleApp() …
bumsfeld 413 Nearly a Posting Virtuoso

Try http://pyarticles.blogspot.com

Where is the meat?

bumsfeld 413 Nearly a Posting Virtuoso

I am scratching my head on this one! However, this modifiecation seems to work correctly ...

num = 32
b2 = 2
x = 1

def increasex3(num, b2, x):
    while num%(b2**x) < num:
        x = x+1
        increasex3(num, b2, x)
    #print x  # test
    return x

result = increasex3(num, b2, x)
print '-->', result
bumsfeld 413 Nearly a Posting Virtuoso

I think you are using wrong word here, list is like an array. You simply want each element of list displayed on separate line, right?

# for instance this is list
cards = ['4 c', '12 h', '2 s', '6 s', '8 s']
 
# one list item per line display
for card in cards:
    print card
 
"""
my output =
4 c
12 h
2 s
6 s
8 s
"""

Edit: changed php tags, don't work properly

bumsfeld 413 Nearly a Posting Virtuoso

Don't use main the way it was written:

def main() :
    renamer(sys.argv[1])
    main()

It might call itself until the recursion limits are reached.

Use it like this:

def main() :
    renamer(sys.argv[1])

main()

Actually the best way to do this is as follows:

import os,shutil 
   
def renamer(target) :    
    os.chdir(target)
    for filename in os.listdir('.') :
        print filename
        newfilename = os.path.splitext(filename)[0] 
        print newfilename
        os.rename(filename, newfilename)
        print "Renamed " + filename + " to " + new_filename
    shutil.copy("copyme","newcopyme"

# test the function/module
if __name__ == __main__:
    renamer(sys.argv[1])

This test allows the program to be importable module or runnable program.

bumsfeld 413 Nearly a Posting Virtuoso

You have to add one important line!

def OnPaint(self, evt):
        dc = wx.PaintDC(self.canvas)
        # added this to keep drawing from messing up on srolling
        self.canvas.PrepareDC(dc)   
        self.vykresli_graf(dc)