snippsat 661 Master Poster

So should we guess how the input file looks like?

snippsat 661 Master Poster

No war,thanks for info nezachem.

snippsat 661 Master Poster
>>> db = {}
>>> h_back = 50
>>> db['hremspace'] = h_back
>>> db
{'hremspace': 50}
>>> heremspace
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'heremspace' is not defined
>>> #So you will get an NameError if hremspace only excit in a dictionary

If this line shall work.
for h_back in hremspace != 3000 :
Somewhere in your code hremspace has to be defined or do you mean to take value for hremspace out off dictionary.

>>> db['hremspace']
50
snippsat 661 Master Poster

I am afraid you are out of luck. w3 asserts that the string "--" (double-hyphen) MUST NOT occur within comments

You see that my script using beautifulSoup can deal with "--" without problem.
I agree that using "--" inside comment is not the best thing to do.

snippsat 661 Master Poster

You just have to put or ask someone to put in python path folder.

>>> import sys
>>> sys.path #list path

One fil BeautifulSoup.py in one off that path and it will work.
Normal is to use this folder for 3-party moduls.
Python26\Lib\site-packages

snippsat 661 Master Poster

BeautifulSoup is a famous python HTML/XML parser.
http://www.crummy.com/software/BeautifulSoup/
BeautifulSoup is only one file BeautifulSoup.py.

build parser like minidom,elementtree should work.
If not 2 of the best is BeautifulSoup and lmxl.
http://codespeak.net/lxml/

snippsat 661 Master Poster

Parser should skip the comments.
I did a test in BeautifulSoup(3.08) dont use newer version.

xml = """
<Label> Hello!</Label>
<!-- The above label says Hello.
  -- It is clear, no?  Let's try spicing it up a bit.
  -- Add some color to it.
-->
<Label color="#FF0000">HI I'M RED-Y.</Label>
"""

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(xml)
matches = soup.findAll('label')
for i,match in enumerate(matches):
    print i, match.text


'''Out-->
0 Hello!
1 HI I'M RED-Y.
'''
PythonNewbie2 commented: Very helpful person! +1
snippsat 661 Master Poster

Thanks everyone. Snippsat, what if you want them with a different number or arguments?

Use the power off python list,dict,set as default argument.
The link tony show the use off *arg(tuple) **arg(dictionary)
Python has much power up it`s sleeves.
Maybe simpler to understand it like this.

def foo(*arg):
    '''Return a tuple'''
    print arg
    
foo(1,2,3,4,5,'test')
foo()


def foo1(**arg):
    '''Return a dictionary'''
    print arg

foo1(a='1', b='2')
foo1()

'''Out-->
(1, 2, 3, 4, 5, 'test')
()
{'a': '1', 'b': '2'}
{}
'''
class Car:
    def __init__(self, carName=['Bmw'], Color=['red'] , Speed=[250]):
        self.name = carName
        self.color = Color
        self.speed = Speed

        self.printStats()

    def printStats(self):
        print 'Car Statistics:'
        print "Name      : %s" % self.name
        print "Color     : %s" % self.color
        print "Speed:    : %s" % self.speed
        print "----------------------------"

car_1 = Car()
car_2 = Car(['fiat','opel','ferrari'], ['black','Blue','Yellow'], [200,220,300])

'''Out-->
Car Statistics:
Name      : ['Bmw']
Color     : ['red']
Speed:    : [250]
----------------------------
Car Statistics:
Name      : ['fiat', 'opel', 'ferrari']
Color     : ['black', 'Blue', 'Yellow']
Speed:    : [200, 220, 300]
----------------------------
'''
snippsat 661 Master Poster

In the above code, why are the three lines following the second for loop encased in parentheses? And what is the last of those three lines.(639-randint? How did they just slap a number and a dash right in front of a function. Thanks for any and all replies.

Why dont you test it out?

>>> from random import * #bad way to import
>>> from random import randint
>>> random_color = (randint(0, 255), randint(0, 255), randint(0, 255))
>>> random_color
(164, 184, 42)
>>> repr(random_color)
'(164, 184, 42)'
>>> random_color = randint(0, 255), randint(0, 255), randint(0, 255)
>>> random_color
(130, 206, 142)
>>> repr(random_color)
'(130, 206, 142)'
>>> #As you see the same

On a side note, why doesn't python support function, method, and constructor overloading? And what does it do to compensate?

Python does not support function overloading but compensate well by use off default arguments and keyword arguments.
There are also rather ugly global statement,that we dont talk about.

def foo(n=None):
    if n is None: n = 10
    return n + 20

print foo()
#-->30

If we talk about a class.
The constructor for a Python class is def __init__(self, ...): and you cannot overload it.
What you can do is use defaults for the arguments.

class Car:
    def __init__(self, carName="Bmw", Color='red', Speed=250):
        self.name = carName
        self.color = Color
        self.speed = Speed

        self.printStats()      

    def printStats(self):
        print 'Car Statistics:'
        print "Name      : %s" % self.name
        print "Color     : %s" % self.color
        print "Speed:    : …
snippsat 661 Master Poster

print list(word_pattern.findall(abstract))

Just a tips.
re.findall is returning a list,so there is not necessary to use list().

import re

text = '''\
hello, my name is george. How are you? Today
i am not feeling very well. I consider myself to be
sick.
'''

word_pattern = re.findall(r'\w+', text)
print word_pattern

""" Out-->
['hello', 'my', 'name', 'is', 'george', 'How', 'are', 'you', 'Today', 'i', 'am', 'not', 'feeling', 'very', 'well', 'I', 'consider', 'myself', 'to', 'be', 'sick']
"""
Gribouillis commented: indeed ! +4
snippsat 661 Master Poster
snippsat 661 Master Poster
def foo():
    from random import *
    print randrange(5,8)

foo()
#--><module1>:1: SyntaxWarning: import * only allowed at module level
5

from random import randrange
def foo():
    from random import *
    print randrange(5,8)

foo()
#-->6

Is there anyway from looking at my code that I can determine which items I need to import from pyExcelerator?

Use dir(pyExcelerator)

>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> help(random.shuffle)
Help on method shuffle in module random:

shuffle(self, x, random=None, int=<type 'int'>) method of random.Random instance
    x, random=random.random -> shuffle list x in place; return None.
    
    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.

>>>
snippsat 661 Master Poster

from pyExcelerator import *

Import shall always be on the top,not inside a function.
That`s why you get this warning.
SyntaxWarning: import * only allowed at module level

DON'T do this:
from pyExcelerator import *
unless you are absolutely sure that you will use each and every thing in that module.
And even then, you should probably reconsider using a different approach.

Better.
from pyExcelerator import <something>
Then use it like this: something()

import pyExcelerator as Ex
Then use it like this: Ex.something()

import pyExcelerator
Then use it like this: pyExcelerator.something()

Example:

#dir(random) #show functions/methods in random
>>> from random import randrange
>>> randrange(1,10)
3
>>> import random as R
>>> R.randrange(5,14)
12
>>> import random
>>> random.randrange(2,8)
6
snippsat 661 Master Poster

thanks for your help, i found a solution, installing C runtime library on the target machine can fix this problem, here is the link if any one needs it :

Yes because it need "MSVCR90.dll".
For Python2.6, this is MSVCR90.dll version 9.0.21022.8, which can be obtained from the Microsoft Visual C++ 2008 Redistributable Package.

The correct dll is in here,not SP1
http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en

If you got it to work with Microsoft Visual C++ 2008 SP1 Redistributable Package.
Then i guess it`s ok.

snippsat 661 Master Poster

Here is the code rewritten in wxpython,so you can compare.
Wxpython is a good gui-toolkit and it look better in windows than Tkinter.
vega_convert_to_wxpython.rar

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
         
        #---| Window color |---#
        self.SetBackgroundColour("light blue")
        
        #---| Panel for frame |---#
        panel = wx.Panel(self)       
        
        #---| Static Text |---#
        self.l1 = wx.StaticText(panel, -1, 'Enter nr x:',
                    pos = (45, 10), size = (150,16 )).SetForegroundColour('blue')
        self.l2 = wx.StaticText(panel, -1, 'Enter nr y:',
                    pos = (45, 60), size = (150,16 )).SetForegroundColour('blue')
        self.result = wx.StaticText(panel, -1, '', pos = (20, 120), size = (200,16))            
        
         #---| Text Boxes |---#
        self.text1 = wx.TextCtrl(panel, pos = (20, 30), size = (100,23))        
        self.text2 = wx.TextCtrl(panel, pos = (20, 80), size = (100,23))
        
        #---| Picture_Button |---#
        self.button1 = wx.BitmapButton(panel, -1 ,wx.Bitmap("8.png"),
                                          pos = (140, 35), size = (55,65))
        self.button1.Bind(wx.EVT_BUTTON, self.button_click)  #*bind to event*#                  
        
    def button_click(self, event):        
        """
        in this case the data items are floating point numbers 
        that are simply added in the example data process
        the result is displayed in a label
        """
        try:        
            x = float(self.text1.GetValue())
            y = float(self.text2.GetValue())
            s = str(x + y)
            self.result.SetLabel(str(s))
        except ValueError:            
            self.result.SetLabel('Enter numeric values for x and y')               
         
#---|Set opp window and show |---#
if __name__ == "__main__":
    app = wx.App()   
    mytitle = 'My window'  
    width = 230
    height = 180
    MyFrame(None, mytitle, (width, height)).Show()
    app.MainLoop()
snippsat 661 Master Poster

A little more on importing.
First the code.

#make_name.py
#saved in python26 folder
def makeName():
    name = raw_input("Please enter your name")
    return name

So how to use it.

>>> import make_name
>>> dir(make_name)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'makeName']
>>> #We look at spesial methods 2 underscore and makName function
>>> make_name.__file__
'C:\\Python26\\make_name.py'
>>> make_name.__name__
'make_name'
>>> make_name.__doc__
>>> #We have not made a doc string in this function
 
>>> make_name.makeName
<function makeName at 0x01DCFCB0>
>>> #We se function makeName and a memory location
>>> make_name.makeName()
Please enter your nameTom
'Tom'
>>> #Call the function,remember we dont need a print statement when we do this in IDLE.

>>> from make_name import makeName
>>> makeName()
#Now i have put make_name in global namespace and can call only function name
snippsat 661 Master Poster

Like this,i have put function call in variable name and age.

def main():    
    name = makename()
    age = makeage()    
    print "You are" ,age ,"years old", name
def makename():
    name = raw_input("Please enter your name ")
    return name
def makeage():
    year = input("What is the year current year? ")
    byear = input("What year were you born in? ")
    age = year - byear
    return age
main()
snippsat 661 Master Poster

The problem is that login from has to run to a javascript.

>>> from twill import get_browser
>>> b = get_browser()
>>> b.go("http://reg3.hu.edu.jo/huregister/")
==> at [url]http://reg3.hu.edu.jo/huregister/[/url]
>>> b.showforms()

Form name=sbmtindex (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
1     user                     text      (None)        
2     pswd                     password  (None)        
3  1  submit                   image     (None)        
4  2  reset                    image     (None)        

>>>

Here we se form detail and the name off form is sbmtindex

<form name="sbmtindex" action="sbmt_index.jsp" method="POST" onsubmit="return checkValues()">

onsubmit is just ignored by mechanize, no javascript interpretation is done.
You need to verify what loginCheck(); in some limited case (Validation) you can do programmatically what javascript does.

So you need a somthing that can handle javascript,to get this to work.
Tools you can look is
http://seleniumhq.org/
http://code.google.com/p/python-spidermonkey/
selenium python bindings to control a real, running browser like Firefox or IE with javascript.

You can try to write code that do the same as javascript.
So there are possible to login but it`s take some more work from your side.

Also found DOMForm.
Client-side HTML processing with JavaScript support.
http://pypi.python.org/pypi/DOMForm/0.0.1a

snippsat 661 Master Poster

For running code once you can write a function like this.

import time

def test():
    "Stupid test function"
    L = []
    for i in range(100):
        L.append(i)

def time_code(arg):
    '''For running code once,and take time'''
    start = time.clock()
    arg()
    end = time.clock()
    print 'Code time %.6f seconds' % (end - start)

if __name__ == '__main__':
    time_code(test)
'''-->Out
Code time 0.000187 seconds
'''

Most off the time you are dealing with code that are to fast to only run once.
That`s where timit is fine.

Here you see that list comprehensions is a litte faster than ordinary for loop.
Here i set timit to run 1000 loops.

import timeit

test = ''' 
L = []
for i in range(1000):
    L.append(i)
    
'''
#-----------#
#The same code as test written with list comprehensions
test_lc = '''
L = [i for i in range(1000)]      
'''

print timeit.Timer(stmt = test).timeit(number=1000)
'''-->Out
2.51438868285
'''

print timeit.Timer(stmt = test_lc).timeit(number=1000)
'''-->Out
1.23845643574
'''
snippsat 661 Master Poster

Pyscripter version 2.0 is out now,support python 2.7.

snippsat 661 Master Poster
>>> l = ['12345'] 
>>> s = ''.join(l)
>>> s
'12345'
>>> len(s)
5
>>> type(l)
<type 'list'>
>>> type(s)
<type 'str'>
>>>
snippsat 661 Master Poster

Try mechanize
http://wwwsearch.sourceforge.net/mechanize/

import mechanize
browser = mechanize.Browser()
browser.open("http://reg3.hu.edu.jo/huregister/")
browser.select_form(nr=0)
browser['user'] = "test"
browser['pswd'] = "123"
response = browser.submit()
html = response.read()
print html

With this a get a 500 error,same same as login with wrong user/pass.

snippsat 661 Master Poster
'''-->my_file.txt
x
a
b
'''

text_label = [f.strip() for f in open('my_file.txt')][0]
self.button = wx.Button(panel, label = '%s' % text_label)

Take x from my_file.txt and place it as label text for button.

snippsat 661 Master Poster
for x in range(5):
   print x,

#the same in C++ is:

for (int x = 0; x < 5; x++)
   cout << x;
//C++
#include <iostream>
using namespace std;
int main()

{
int size;
size = 4;

    for (int i = 0; i < size; i++)
        cout << '*' <<endl;
    return 0; 
}

#python
size = 4

for i in range(size):
    print '*'

#A python function for this
def asterix(num, lenght):
    a = '*' * num
    for i in range(lenght):
        print a

asterix(4,4)

'''-->Out
****
****
****
****
'''
snippsat 661 Master Poster
snippsat 661 Master Poster

Using global is not a good soultion at all,learn to give argument at return value out functions.
A simple example.

def newUser():    
    Username = raw_input('Choose a username? ')
    return Username


def reg_user(newUser):
    '''Make 3 users an save to a list'''
    l = []
    for i in range(3):
        l.append(newUser())        
    return l   
    
if __name__ == '__main__':     
    print reg_user(newUser)

'''-->Out
Choose a username? Tom
Choose a username? Paul
Choose a username? Hans
['Tom', 'Paul', 'Hans']
'''
snippsat 661 Master Poster

Think about your design.
One textbox user enter 3 number.
Then operator / and then user enter new number and you get and average.
Like a normal calculator.

What if user want average of 5 number,should you create 5 textboks?

snippsat 661 Master Poster
>>> import texttable
>>> dir(texttable)
['ArraySizeError',
 'Texttable',
 '__all__',
 '__author__',
 '__builtins__',
 '__credits__',
 '__doc__',
 '__file__',
 '__license__',
 '__name__',
 '__package__',
 '__revision__',
 '__version__',
 'len',
 'string',
 'sys',
 'textwrap']


>>> table = Texttable()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'Texttable' is not defined


table = texttable.Texttable()  #ok
#We change import line
from texttable import Texttable

table = Texttable()
table.set_cols_align(["l", "r", "c"])
table.set_cols_valign(["t", "m", "b"])
table.add_rows([ ["Name", "Age", "Nickname"], ["Mr\nXavier\nHuon", 32, "Xav'"], ["Mr\nBaptiste\nClement", 1, "Baby"] ])
print table.draw()

'''-->Out
+----------+-----+----------+
|   Name   | Age | Nickname |
+==========+=====+==========+
| Mr       |     |          |
| Xavier   |  32 |          |
| Huon     |     |   Xav'   |
+----------+-----+----------+
| Mr       |     |          |
| Baptiste |   1 |          |
| Clement  |     |   Baby   |
+----------+-----+----------+
'''
snippsat 661 Master Poster

Something like this maybe.

import re

html = '''\
"<meta http-equiv='content-type' content='text/html; cHarSet=gBk' />"
'''

test_match = re.search(r'cHarSet\=(\w*)', html)
print test_match.group()
#-->cHarSet=gBk
print test_match.group(1)
#-->gBk
snippsat 661 Master Poster
import time

def foo():
    for i in range(100000):
        i

def time_code(arg):    
    start = time.clock()
    arg()
    end = time.clock()
    print 'Code time %.3f seconds' % (end - start)

if __name__ == '__main__':
    time_code(foo)

Most off the time code is to fast to measure only with one run,that`s why man use timeit modulen for measurement of code time.
From command line or script.

C:\>python -m timeit "for i in xrange(100): pass"
1000000 loops, best of 3: 1.77 usec per loop

#Are tuple faster than list?
C:\>python -m timeit (1,2,3,4)
10000000 loops, best of 3: 0.0226 usec per loop

C:\>python -m timeit [1,2,3,4]
10000000 loops, best of 3: 0.194 usec per loop
#Yes tuple are faster than list
snippsat 661 Master Poster

Now i have newest version off wxpython installed.

snippsat 661 Master Poster

Gui2exe work fine with python 2.6
It give a depreached warning,but that dont matter it works fine.

snippsat 661 Master Poster

Something like this,look into findall off re module.
Dont use str as variable,it`s a builtin key word.

>>> str
<type 'str'>
>>> help(str)
Help on class str in module __builtin__:
>>> import re
>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.
    
    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.
    
    Empty matches are included in the result.
import re

text = '''\
Subs cars are test driving in space,and many pigs are flying.
'''

test_match = re.findall(r'\w+[s]\b', text)
print test_match
#->['Subs', 'cars', 'pigs']
snippsat 661 Master Poster

Yes,forgot sorted by lenght was thinking alphabetically sort.
Thanks tony.

snippsat 661 Master Poster
def wordPop(text, n):
    nwords = []
    words = text.split()
    for word in words:
        if (len(word) >= n):
             nwords.append(word)
    return sorted(nwords)

w = 'This is a test off word lenght'
print wordPop(w.lower(), 4)
#->['lenght', 'test', 'this', 'word']

So i removed you length_compare function.
sorted(nwords,cmp=length_compare)
So this get wrong,first off cmp is a python key word.
And your "length_compare" function is not comparing anything.

>>> cmp
<function length_compare at 0x0265EF30>
>>> help(cmp)
Help on function cmp=length_compare in module __main__:

length_compare(x, y)
def length_compare(x, y):
    return len(x) - len(y)

x = 'hi'
x = 'test'
print length_compare(x, y)  #->2
#If you call function you have to use 2 argument
#And it`s not comparing anything,just extract test(4) from hi(2)
snippsat 661 Master Poster

I'm writing a code that should extract tags from an HTML code

When comes html regex may not be the right tool.
Look into beautifulsoup and lxml.

Read this answer by bobince about regex/html,one of the best answer i have read and funny to.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

Here is one way.

import re

html = """\
<div style="background: url(/groups/roundedcorners?
c=999999&bc=white&w=4&h=4&a=af) 0px 0px; width: 4px; height: 4px">
Ask how to use HTMLParser
</div>"""

test_match = re.sub(r'<.*?>|<\w{3}', '', html)
print test_match 

'''-->Out
 style="background: url(/groups/roundedcorners?
c=999999&bc=white&w=4&h=4&a=af) 0px 0px; width: 4px; height: 4px">
Ask how to use HTMLParser
'''
snippsat 661 Master Poster

Always specify the exceptions to catch.
Never use bare except clauses.
Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.

Let you code run if you catch new exception,you can put them in except(all my catch)

try:
    x = float(raw_input('Enter the first number: '))
    y = float(raw_input('Enter the second number: '))
    print x / y
except (ZeroDivisionError, TypeError, ValueError):
    print 'Your numbers were bogus...'

Or you can split it upp.

try:
    x = float(raw_input('Enter the first number: '))
    y = float(raw_input('Enter the second number: '))
    print x / y
except ZeroDivisionError:
    print "The second number can't be zero!"
except ValueError:
    print "That wasn't a number, was it?"
snippsat 661 Master Poster

If you use findall you can use something simple as this.

import re

text = '''\
my open verb in in red box test kk55 with me as key.
'''

test_match = re.findall(r'open|red|box|with|key' ,text)
print test_match
#->['open', 'red', 'box', 'with', 'key']

Not groups but a list you can use.

print test_match[2]
#->box
snippsat 661 Master Poster
snippsat 661 Master Poster

>>>E:\1py\freeze>python my_cx_freeze.py build

You are running from IDLE python shell,that`s not command line.
Dont you understand what command line is?

Windows you push start->run(write cmd)
Then command shell start.
Then you navigate using cd to the dir where you have your py-files.

snippsat 661 Master Poster

I am using command line and I tried using the line of code you gave me and it gives me syntax error: invalid syntax

Then you are doing something wrong,what we dont know because you dont post any code.
We are not mindreaders.

snippsat 661 Master Poster

do I have to save it in a certain spot because It's just keeps telling me invalid syntax

Have you look at my post it should be clear?

You have to run it from command line.
Start->run->cmd

cxfreeze hello.py --target-dir dist
do I have to save it in a certain spot because It's just keeps telling me invalid syntax

This is more a pseudo explations,and will off course give you and syntak error if you dont change it.

E:\1py\freeze>python my_cx_freeze.py build #This is the line that start build process
(Your path)python my_cx_freeze.py build    #Change to wish dir you like

This run the my_cx_freeze.py that has a link to the program i want to make exe of.
Wish is in my case was date.py

snippsat 661 Master Poster

Testet this out with python 2.65
This should work for python 3.xx to.
Made a dir E:\1py\frezze
In that dir i have 2 files.

#cx_freeze test save in dir E:\1py\freeze
#date.py
import time

date_old = "05.26.1999"

#Use strptime(time_str, format_str) to form a time tuple
time_tuple = time.strptime(date_old, "%m.%d.%Y")

#Use time.strftime(format_str, time_tuple) to create new format
date_new = time.strftime("%b-%d", time_tuple)

print(date_old)  # 14-05-1999
print(date_new)  # May-14
raw_input('press enter to exit!')
#Cx_freeze test save in dir E:\1py\freeze
#my_cx_freeze.py
"""
con_setup.exe

Using cx_freeze with Python31 to package a console
program to an executable file (.exe in Windows OS).

Might want to put a console-wait-line in at the end of your program.

Put this setup program and your console program file into the same 
directory.  Change the filename in this setup program and also edit 
name, version and description in setup() if you so desire.

Run the build process by running the command: 
python con_setup.py build

A directory 'build' is created with a subdirectory 'exe.win32-3.1'
containing all the files needed for distribution including the 
.exe file named after the console program file.

The total distribution has a size of about 4.2 Mb.
"""

from cx_Freeze import setup, Executable

# change the filename to your program file
filename = "date.py"

setup(
    name = "date",
    version = "1.0",
    description = "console cx_Freeze script",
    executables = [Executable(filename)])

So then i have 2 files in E:\1py\freeze(date.py and my_cx_freeze.py)

#From cmd
c:\e:
E:\cd 1py
E:\1py\cd freeze
E:\1py\freeze>python my_cx_freeze.py build …
snippsat 661 Master Poster

<open file 'MyText1.txt', mode 'r' at 0x15a69b0>
Can someone explain? I'm on a Mac.

You dont make any action for the file object.
text = open(fname, "r").read()
Now it will read file into memory and you can print it out.

So if you call "printWordFrequencies" like this it will work.
printWordFrequencies(text)
doctest.testmod(verbose=True)

Dont ask question in Code Snippet,make a new post next time.

snippsat 661 Master Poster

As ultimatebuster explain return get you out of a function and break get you out off a while loop.
An example.

def find_father():
    pass

def main():
    '''Main menu and info ''' 
    while True:               
        print 'Father finder'
        print '(1) 1 - Find a Father'        
        print '(Q) Quit' 
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            find_father()       
        elif choice.lower() == 'q': 
            return #Get out of while loop
        else: 
            print 'Not a correct choice:', choice 

if __name__ == '__main__':
    main()

I we take out while loop out off the function,we use break.

while True:               
    print 'Father finder'
    print '(1) 1 - Find a Father'        
    print '(Q) Quit' 
    choice = raw_input('Enter your choice: ') 
    if choice == '1':
        print 'Find father'      
    elif choice.lower() == 'q': 
        break #Get out off the while loop
    else: 
        print 'Not a correct choice:', choice
snippsat 661 Master Poster

Keep aspect ratio of the image.

from PIL import Image

def resize(img,percent):
    ''' Resize image input image and percent | Keep aspect ratio'''
    w,h = img.size
    return img.resize(((percent*w)/100,(percent*h)/100))

if __name__ == '__main__':
    img = Image.open('s.jpg')
    #Give argumet to function image and percent
    resized_image = resize(img, 80)
    resized_image_file = 's_new.jpg'
    resized_image.save(resized_image_file)
    print("%s saved!" % resized_image_file)
snippsat 661 Master Poster

For this i think a dictionary approach is most natural.
@Beat_Slayer test your code.

Edit:

lets suppose, South Africa.

South Africa work fine in mine code.
A7 is South Africa

countries = [i.strip() for i in open('countries.txt')]
#Bad variables list
var_list = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']

countries_Dict = dict(zip(var_list, countries))
print (countries_Dict)

#Iterate over Dict
for k,v in countries_Dict.items():
    print ('%s is %s' % (k, v))

'''Out-->
{'A1': 'england', 'A3': 'spain', 'A2': 'america', 'A5': 'germany', 'A4': 'brazil', 
A1 is england
A3 is spain
A2 is america
A5 is germany
A4 is brazil
A6 is australia
'''
snippsat 661 Master Poster
>>> x = 'car'
>>> x.close()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'close'

As tony mention str has no close() method as a file object.

cStringIO module has close(),or maybe you are trying to use close on what you think is a file object.
You can check type like this.

>>> x = 'car'
>>> type(x)
<type 'str'>
>>>
#cStringIO demo
>>> from cStringIO import StringIO
>>> output = StringIO()
>>> output.write('This goes into the buffer.\n')
>>> output.write('car')
>>> print output.getvalue()
This goes into the buffer.
car
>>> output.close() # discard buffer memory
snippsat 661 Master Poster

I pretty much give you the answer.
"05/26/1999" should be covert to May-26,look at my first code.
Then rebuild your function with that code.
Get the function to work first then you can think of exception handling.

I see an other approach by tony using datetime module,that also work fine.
Tony can also use this format 01.12.2020.

For that to work we have to change like this in my code.

>>> date_old = '05.26.1999'
>>> time_tuple = time.strptime(date_old, "%m.%d.%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>

Or write something better that can handle both or more format.

snippsat 661 Master Poster

This should help you.

>>> import time
>>> date_old = '05/26/1999'
>>> time_tuple = time.strptime(date_old, "%m/%d/%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>
try:
    # use strptime(time_str, format_str) to form a time tuple
    time_tuple = time.strptime(date_old, fmt)
except: #Dont use bare except try to catch specific error that are comming
        #Example except ValueError or something else.
    pass