snippsat 661 Master Poster

That way is a little unpythonic way to do it rrashkin.

d = {'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0}
for k,v in d.items():
    if v == 0:
        del d[k]

print d
#--> {'Five': 34, 'Four': 45, 'One': 10, 'Seven': 22, 'Three': 35}

For both dictionary and list it's not so normal to use del.
Here create a new dictionary using dict comprehension,as you see no del.

>>> d = {'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0}
>>> {k:v for k,v in d.items() if v != 0}
{'Five': 34, 'Four': 45, 'One': 10, 'Seven': 22, 'Three': 35}

Just to show the same with a list.

>>> lst = [1, 2, 0, 4, 0, 3, 0, 2, 0, 2]
>>> [i for i in lst if i != 0]
[1, 2, 4, 3, 2, 2]
snippsat 661 Master Poster

Make a list index out of range error.

>>> lst = [1,2,3]
>>> lst[2]
3
>>> lst[3]
Traceback (most recnt call last):
  File "<interactive input>", line 1, in <module>
IndexError: list index out of range

So it should be easy to understand if you look at list(print or repr).
Then you see that index you try use is out of list range.

This can mean that meta.getheaders("Content-Length") is returning an empty list.
The if you index it with [0],the empty list give back list index out of range error.
which might happen if something went wrong in the urlopen call.

snippsat 661 Master Poster

1.is is used for web development

Python is great for all web stuff you can think of.
Is normal to use Web Framework when making websites.
Django is the most known and has good documentation,some sites run bye Django djangosites.
Some info about setup Apache with mod_wsgi/mod_python here
HOWTO Use Python in the web

There are also CMS like Plone and Django CMS.

Micro framework has in the last couple of year become very popular, Flask, Bottle, Pyramid to mention some.

There a lot of more stuff that make Python great to interact with web,as honorable mention Requests: HTTP for Humans, Beautiful Soup, lxml

snippsat 661 Master Poster

Python has a scheduler module,wish is a option to OS scheduler like Cron or Windows task scheduler.
I have used it's some times and it work well sleeping in background and do work only when it shall.
One positive aspect is that is crossplatform.

So this will run every 2 hours.

from bs4 import BeautifulSoup
import re
import urllib2
import sched, time

def do_event():
    url = "http://www.boston.com/yourtown/"
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page.read())
    news_titles = soup.find_all('h4')
    for nts in news_titles:
        for n in nts("a"):
            print n.renderContents()
    s.enter(7200, 1, do_event, ())

s = sched.scheduler(time.time, time.sleep)
s.enter(7200, 1, do_event, ())
s.run()
Gribouillis commented: good idea +14
snippsat 661 Master Poster

The Problem with Integer Division
Not much else to say if you read that post.
One tips is to use from __future__ import division for Python 2.x.
Python 3.x has made chage to integer-division.

#Python 2.7
>>> 10 / 3
3
>>> from __future__ import division
>>> 10 / 3
3.3333333333333335

--

#Python 3.3
>>> 10 / 3
3.3333333333333335
Gribouillis commented: good link +14
snippsat 661 Master Poster

if there are more number of parameters, out of which we need to print version and type only

can you please help with the code to get out this

You have to post an example of how the other parameters look.
There are many ways to do this,if data is unformatet/changing regex can be and option.

import re

data = '''\
abc : 123
version: 7.0.0.9
type : NAS
ggg.2 : 4444
version: 8
type : FOO
hg.1234: test'''

result = re.findall(r"version.*|type.*", data)
print result
print zip(*[iter(result)]*2)
print [tuple(x.strip() for x in y.split(":")) for y in result] 

"""Output-->
['version: 7.0.0.9', 'type : NAS', 'version: 8', 'type : FOO']
[('version: 7.0.0.9', 'type : NAS'), ('version: 8', 'type : FOO')]
[('version', '7.0.0.9'), ('type', 'NAS'), ('version', '8'), ('type', 'FOO')]
"""
snippsat 661 Master Poster

Give an example or link og what you try to extract/parse.
As mention by krystosan it's XML data,and there are good tool for this in Python.
And library that is only for parsing RSS like Universal Feed Parser
I like both Beautifulsoup and lxml.
A quick demo with Beautifulsoup.

from bs4 import BeautifulSoup

rss = '''\
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>Python</title>
<link>http://www.reddit.com/r/Python/</link>
<description>
news about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python
</description>'''

soup = BeautifulSoup(rss)
title_tag = soup.find('title')
description_tag = soup.find('description')
print title_tag.text
print description_tag.text

"""Output-->
Python

news about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python
"""
snippsat 661 Master Poster

Fun this odd/even stuff,one with ternary operator.
Did like the clean look of this one.

>>> from collections import Counter
>>> from random import sample
>>> Counter("Odd" if i % 2 else "Even" for i in sample(range(0, 1000), 100))
Counter({'Even': 56, 'Odd': 44})
snippsat 661 Master Poster

This is a compressed version,if you see me post in link you see more how it works in part.

>>> from collections import Counter
>>> import random
>>> Counter(map(lambda x : 'even' if x % 2 == 0 else 'odd', (random.randint(0,1000) for i in range(100))))
Counter({'even': 58, 'odd': 42})
snippsat 661 Master Poster
>>> from collections import OrderedDict
>>> s = "Mathematics".upper()
>>> ''.join(OrderedDict.fromkeys(s))
'MATHEICS'
snippsat 661 Master Poster

Download numpy for Python 3.3 here,try again.

snippsat 661 Master Poster

Date and time measurement is a complex area full of tricky problems and unexpected edge-cases.
This is why we have and should use libraries for this.
It can of course be fun to do this manually,but also painful if you try for a long periods of time like this.

Just a demo how it can look with datetime module.

import datetime

date = datetime.date(1901, 1, 1)
days = 0
while date.year < 2001:
    if date.weekday() == 6 and date.day == 1:
        days += 1
    date += datetime.timedelta(days=1)

print 'Sundays that felled on the first month during the twentieth century was {}'.format(days)

"""Output-->
Sundays that felled on the first month during the twentieth century was 171
"""
ddanbe commented: Nice answer. +14
snippsat 661 Master Poster

sorry, but what prevents the code from only ever reaching the first '****optimisation achieved****' and counting that line repeatedly?

Here is an another way to this.
Here i want to get file name and count back,and also correct line number back.

file_1.txt:

fire
fox
**** Optimisation achieved ****

file_2.txt:

**** Optimisation achieved ****
car ¨
123
**** Optimisation achieved ****
**** Optimisation achieved ****
**** Optimisation achieved ****

file_3.txt:

**** Optimisation achieved ****
hello
world
**** Optimisation achieved ****

So a manual count would be.
file_1 has 1 "Optimisation" count at line 3
file_2 has 4 "Optimisation" count at line 1,4,5,6
file_3 has 2 "Optimisation" count at line 1,4

Some code for this.

import re
from glob import glob

count = {}
line_numb = []
for files in glob('*.txt'):
    #print(files)
    with open(files) as f_in:
        for num, line in enumerate(f_in, 1):
            line = line.strip()
            if '**** Optimisation achieved ****' in line:
                count[f_in.name] = count.get(f_in.name, 0) + 1
                line_numb.append(num)
        line_numb.append(f_in.name)

line_numb = ' '.join(str(i) for i in line_numb)
line_numb = re.split(r'\w+.txt', b)
line_numb.pop()
opt_count = (sorted(count.items(), key=lambda x: x[0]))

print('-'*5)
print(line_numb)
print(opt_count)
print('-'*5)

with open('result.txt', 'w') as f_out:
    for line, count in zip(line_numb, opt_count):
        print('{} has "Optimisation" count of {}\n"Optimisation" occur at line nr: {}\n'.format(count[0], count[1], line.strip()))
        #f_out.write('{} has "Optimisation" count of {}\n"Optimisation" occur at line nr: {}\n'.format(count[0], count[1], line.strip()))


"""Ouptput-->
-----
['3 ', ' 1 4 5 6 ', ' 1 4 ']
[('file_1.txt', 1), ('file_2.txt', 4), ('file_3.txt', …
snippsat 661 Master Poster

Use urlretrieve,something like this.

import winsound    
try:
    # Python2
    from urllib import urlretrieve
except ImportError:
    # Python3
    from urllib.request import urlretrieve

def play(sound):
    winsound.PlaySound(sound, winsound.SND_FILENAME)

# Download wave file and save to disk
url = "http://www.villagegeek.com/downloads/webwavs/adios.wav"
filename = url.strip().split('/')[-1]
urlretrieve(url, filename)
print("Sound saved as {}".format(filename))

# Play wave file
play(filename)
snippsat 661 Master Poster

How about this someone told me about:

The code is terrible and not working.

There must be a shorter way of doing that too :)

def word_reverser(word_in):
    return word_in[::-1]

user_input = raw_input('Type anything and hit enter: ')
d = word_reverser(user_input)
print("Eek, what's this?! ==> {}".format(d))
snippsat 661 Master Poster

IMO, VS2010 with PythonTools 1.5 is the best IDE.

Say that you mean that,don't speak for everyone.

PyScripter has alot of glamour, but it doesn't have an interactive interpreter

PyScripter has always had a interactive interpreter.

Spyder is ok,and istall with winpython,to get a lot of tools as addon.

is there anything like VS but with more glamour and conveniency??

Not free but has a lot stuff like VS.
PyCharm a newer big IDE for python.
Supported: Python 2.x or 3.x, Jython, IronPython and PyPy,Django.....

Wingware
KomodoIDE

snippsat 661 Master Poster

I need to do simple things like list the file and folders in a directory 'ls' and change director 'cd'. I found these two pages that looked promesing but I still didn't fine what I was looking for. Any ideas?

Maybe you need to broaden your Python knowledge,because this is basic stuff when working with files and folders in Python.

list the file and folders os.listdir(), glob.glob() or os.walk()
os.walk() will recursively walk a directory,means that it will find all subfolders and files.

change director 'cd' os.chdir(path)
os.getcwd() # Returns the current working directory
os.chdir('/path/to/directory') Change the current working directory to 'path/to/directory'.
Also accepts bash commands like '..' and '/'.

snippsat 661 Master Poster

Can use isinstance.

>>> weight = float(raw_input("enter the weight: "))
enter the weight: 100.0
>>> weight
100.0

>>> type(weight)
<type 'float'>

>>> isinstance(weight, float)
True

>>> isinstance(weight, int)
False

>>> weight = 50
>>> isinstance(weight, float)
False

>>> #If you want both int and float to be True
>>> isinstance(weight, (int,float))
True

>>> a = 'hello'
>>> isinstance(a, (int,float))
False

As info.
In Python type checking is someting we try to avoid.
A couple lines you sure will hear more about if you continue to use Python.

If it looks like a duck, quacks like a duck - it's a duck.
it's Easier to Ask Forgiveness than Ask Permission.

snippsat 661 Master Poster

i dont need it in a list i need bal to be set as a variable so:
top_line = ball
bottom_line = red

You should have be able to figure this out,with the help you already got.

import itertools as itt

def wrong_line(line):
    return 'card 1:' not in line

with open('filename.txt') as ifh:
    result = list(itt.islice(itt.dropwhile(wrong_line, ifh), 1, 3))

top_line, bottom_line = [i.strip() for i in result]
print top_line #ball
print bottom_line #red

----

search_word = 'card 1'
with open('filename.txt') as f:
    for line in f:
        if search_word in line:
            top_line = next(f).strip()
            bottom_line = next(f).strip()

print top_line #ball
print bottom_line #red
snippsat 661 Master Poster

The list show only integer,so why convert at all.

>>> lst = [120, [10, 20, 30]]
>>> lst[0]
120
>>> lst[1]
[10, 20, 30]
>>> type(lst[0])
<type 'int'>

>>> balance, withdrawal = lst[0], lst[1]
>>> balance
120
>>> withdrawal
[10, 20, 30]
snippsat 661 Master Poster

That gives wrong output james.lu.75491856.
There is no need to split and loop over words.

input_string = raw_input("Input")
print input_string[::2]
snippsat 661 Master Poster
snippsat 661 Master Poster

What is the purpose of this?

I wonder about this to.

I'm wondering if it is possible to pass formatted strings to function arguments.

Yes a formatted string is still a string and function can take most datatypes.
I dont see the point of splitting the format option into two part.

def task(arg):
    return arg

#Why not one part,if string is to long escape with \
OUT_TASK = "Task_{id1}, FUNCTION, {id2}, task{id3}_types, None"\
.format(id1=100, id2='doNothing', id3=300)

print task(OUT_TASK)

Can do something like this with *args,but ugly and hard to understand.

def task(*args):
    return args[1]

OUT_TASK = "Task_{id1}, FUNCTION, {id2}, task{id3}_types, None"
print task(OUT_TASK, OUT_TASK.format(id1=100, id2='doNothing', id3=300))
snippsat 661 Master Poster

Shorter.

>>> strng = '1002-1004,1 1444'
>>> re.findall(r'\W', strng)
['-', ',', ' ']

Or the same without regex.

>>> strng = '1002-1004,1 1444'
>>> [c for c in strng if c in ['-', ',', ' ']]
['-', ',', ' ']
snippsat 661 Master Poster

i have even re installed pywin32 but still

Strange.
Ok here are files.
http://pastelink.me/dl/0b94d2

snippsat 661 Master Poster

ImportError: No module named 'win32com.gen_py'
when i run your cx_run.py script

Hard to say because it works for me.
Some info.
win32com.gen_py is part of Pywin32 package.
Placement on my hdd is C:\Python27\Lib\site-packages\win32com\gen_py
See if you have this placement.

Make sure that Environment Variables is set to python27.
http://www.nextofwindows.com/how-to-addedit-environment-variables-in-windows-7/
To path add ;C:\python27\;C:\python27\scripts

snippsat 661 Master Poster

I have done some tesing and got it to work(windows 7 Ultimate)
First my test code.

#sound_test.py
import pyttsx
import time
from datetime import date
from datetime import datetime

engine = pyttsx.init()

date = date.today()
time_now = datetime.now()
date = date.strftime("%A %d %B")
time_now = time_now.strftime('%H:%M:%S')

engine.say('The date is {} and time is now {}'.format(date, time_now))
time.sleep(1)
engine.runAndWait()

Cx_freeze setup.

#cx_run.py
from cx_Freeze import setup,Executable

includes = ["pyttsx", "pyttsx.drivers.sapi5"]
excludes = []
packages = ['win32com.gen_py']

filename = "sound_test.py"
setup(
    name = 'myapp',
    version = '0.1',
    description = 'test pyttsx',
    author = 'no',
    author_email = 'someting@my.org',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'includes':includes}},
    executables = [Executable(filename, base = "Win32GUI", icon = None)])

The hard part to figure out was pyttsx.drivers.sapi5 and win32com.gen_py
To run it sound_test.py and cx_run.py in same folder(freeze).
From command line(cmd)
C:\freeze>python cx_run.py build

snippsat 661 Master Poster

As posted over itertools izip is ok to use and fast.
Python has also build in zip

>>> zip(names,surnames)
[('Jake', 'Cowton'), ('Ben', 'Fielding'), ('Rob', 'Spenceley Jones')]

---

for first,last in zip(names,surnames):
    print first,last

    Jake Cowton
    Ben Fielding
    Rob Spenceley Jones        
snippsat 661 Master Poster
dir(__builtins__)
#list of what's in the built-in namespace

If you not sure do a simple test.
You get a NameError if python can't find the name.

>>> reload
<built-in function reload>

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

>>> list
<type 'list'>

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

So my_reload and lst is ok names to use.
Also pay attention to modules names,so dont name someting random.py
When Python has a module named random.

snippsat 661 Master Poster
TrustyTony commented: You could do worse than listen to Alex Martelli +12
snippsat 661 Master Poster

Ok project,some advice or tips.
I would have have used datetime module and not wirte getMom function,because there are many dark spots
when trying to date stuff yourself.

>>> from datetime import date
>>> d = date.today()
>>> d.strftime("%B")
'April'
>>> d.strftime("%A, %d. %B %Y %I:%M%p")
'Sunday, 28. April 2013 12:00AM'

Many elif in getMom function,there are some way to shorten it.
Both list and dictionary is an option here.
Here a example with list and enumerate().

def get_month(m):
    m_lst = ['january', 'february', 'march']
    for index,month in enumerate(m_lst, 1):
        if m == index:
            return month

Test.

>>> get_month(1)
'january'
>>> get_month(3)
'march'
otengkwaku commented: thanks for will post the revised version soon +2
snippsat 661 Master Poster

hmm you have ask similar question before and got good answers.
So two word in s1.

>>> s1 = "Hello World"
>>> len(s1.split())
2

Some really basic mistake.
What happends if you iterate before you split() like you do?

s1 = "Hello World"
for word in s1:
    print word #?

s1 and s2 this dos dos not mean concatenate s1 with s2.
and or not are logical operators,is in every Python tutorial/book.
and,If both the operands are true then then condition becomes true.

Fix.

def count_word():
    s1 = "Hello World"
    s2 = "Computer Programming for Kids and Other Beginners"
    numCount = 0
    for word in s1.split() + s2.split():
        numCount += 1
    print "Total strings is", numCount

count_word()

Better.

s1 = "Hello World"
s2 = "Computer Programming for Kids and Other Beginners"    
total_words = s1.split() + s2.split()

print len(total_words)    
sort_key = lambda s: (-len(s), s) #in case of equality by the alphabetical order?
print sorted(total_words, key=sort_key)
snippsat 661 Master Poster

I think import can be used to access functions from another .py file but I'm not sure and haven't used it yet

Yes and here dos if __name__ == "__main__": play and important part.
You have made a fantastic name multiplier code,and you whant to import it so you can use it in other code or share it.
Version 1.

#name_multiplier.py
def name_multiplier(*arg):
    return arg * 2

#Tests
print name_multiplier('hello', 'world')
print name_multiplier(1, 9)

Save it as name_multipler.py in PYTHONPATH,just use python27 folder or your version of Python folder.
Now code is an module and you can import it,ohh easy.
Test it out.

>>> import name_multiplier
('hello', 'world', 'hello', 'world')
(1, 9, 1, 9)

Hmm i dont want test code to get run when i import it.
Version 2.

#name_multiplier.py
def name_multiplier(*arg):
    return arg * 2

if __name__ == '__main__':
    #Tests
    print name_multiplier('hello', 'world')
    print name_multiplier(1, 9)

Test it out.

>>> import name_multiplier
>>> #Now it works as it should and dont run test code
>>> name_multiplier.name_multiplier('a', 5)
('a', 5, 'a', 5)

>>> #I want to type name_multiplier 1 time
>>> from name_multiplier import name_multiplier
>>> name_multiplier('.', '_','~')
('.', '_', '~', '.', '_', '~')

So in version 2 it work as a standalone program and also as a module should(not run code when import is used)

snippsat 661 Master Poster

so maybe newFile can be temporary and then it can be used with to reoverwrite the oldFile?

Yes this is normal way,you iterate over contend and do what you need,then save contend in a new file.
If you need newtext to be oldtext you rename the files.
os.rename(oldtext','newtext') or shutil.move('oldtext','newtext')

Python has fileinput that can do inplace edit of orginal file.
It's ok,but the method over with rename is just as good.
If order doesn't matter,soultion by pyTony is good.

'''lines.txt-->
line 1
line 2
line 2
line 3
'''

import fileinput
import sys

def remove_dup(fname):
    text = []
    for line in fileinput.input(fname, inplace=True):
        if line not in text:
            text.append(line)
            sys.stdout.write(line)

fname = 'lines.txt'
remove_dup(fname)

'''lines.txt-->
line 1
line 2
line 3
'''
snippsat 661 Master Poster

A little more about *args and **kwargs

First vehicle take only 'car' as agument.
Next *args take 'hello', 'world' and make it a tuple.
Next **kwargs take key_a='value 1', key_b='value 2' and make it a dictionary.

def func(vehicle, *args, **kwargs):
    #argument vehicle
    print(vehicle) #--> car

    #argument *args
    print(args) #--> ('hello', 'world')
    print(args[1]) #--> world

    #argument **kwargs
    print(kwargs) #--> {'key_b': 'value 2', 'key_a': 'value 1'}
    print(kwargs['key_a']) #--> value 1


func('car', 'hello', 'world', key_a='value 1', key_b='value 2')

*args can take many arguments.

def bar(*args):
    print(sum(args)) #--> 45

bar(1,2,3,4,5,6,7,8,9)

**kwargs can take many arguments.
So here iterate over dictionary and print key --> value.

def foo(**kwargs):
    for key in kwargs:
        print("Values from dict--> {}: {}".format(key, kwargs[key]))

foo(Name='Zara', Age=7, Class='first')

"""Output-->
Values from dict--> Age: 7
Values from dict--> Name: Zara
Values from dict--> Class: first
"""
snippsat 661 Master Poster

Some hint,it's ok to use total += number as practice.
Here i do the same with build in sum().

"""
randomnumbers.txt-->
1 4 5
2 4 8
"""

with open('randomnumbers.txt') as f:
    print sum(float(i) for i in f.read().split()) #24.0

So this sum up all numbers in one go.
Split it up to show what's going on.

with open('randomnumbers.txt') as f:
    str_lst = f.read().split()
    print str_lst #--> ['1', '4', '5', '2', '4', '8']

    #Convert str_lst to integer or float
    lst = [int(i) for i in str_lst]
    print lst #--> [1, 4, 5, 2, 4, 8]

    #Sum up numbers in lst
    print sum(lst) #--> 24

    #Total numbers in file
    print len(lst) #--> 6

Not use sum().

lst = [1, 4, 5, 2, 4, 8]
total = 0.0
for numbers in lst:
    total += numbers

print total #--> 24.0
snippsat 661 Master Poster

A more pythonic/better solution is to use enumerate()
enumerate() can take argument,so counting start at 1.

with open('names.txt') as fin:
    for index, name in enumerate(fin, 1):
        print("{}: {}".format(index, name.strip()))

"""Output-->
1: Fred
2: Mary
3: Lisa
4: Amy
"""
snippsat 661 Master Poster

don't work

Don't do this now code is ugly and obfuscated.
Read PEP-8,try to follow advice in PEP-8.

It can be fun to fit a lot of code into one line,this is most for fun and compositions like Golf code

(M. Fowler)
Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.

nouth commented: I like the sound of Code Golf, can't wait to try it out and wouldn't have ever have found it if it weren't for this post :) +0
snippsat 661 Master Poster

think I solved it :)

Yes that look good.
Can clean it up little.
word[:-1] is more common to use word.strip()

>>> s = 'bar\n'
>>> s
'bar\n'
>>> s.strip()
'bar'

So then it can look like this,remove if not word: break

with open("textfileA.txt") as a, open("textfileC.txt", 'w') as c:
    for word in a:
        word = word.strip()
        with open("textfileB.txt") as b:
            for line in b:
                line = line.strip()
                if word in line:
                    c.write('Error: {} -in-> {}'.format(word, line))
nouth commented: thanks :) +0
snippsat 661 Master Poster

textfileB: "word","word","word"

So dos your text file look like this when you read it?

with open("textfileB.txt") as f:
    your_file = f.read()

print your_file

Can you post the output?
The reason why i ask is because it not normal to have quotes in file.
If it's quotes you have to remove them,so you can get word without quotes.

>>> your_file
'"foo","bar","hello"\n'
>>> your_file.split(',')
['"foo"', '"bar"', '"hello"\n']
>>> your_file.split(',')[0]
'"foo"'
>>> print your_file.split(',')[0]
"foo" #You see it's not the word foo, but "foo" 

Remove quotes.

>>> [i.strip().strip('"') for i in your_file.split(',')]
['foo', 'bar', 'hello']
>>> [i.strip().strip('"') for i in your_file.split(',')][0]
'foo'
>>> print [i.strip().strip('"') for i in your_file.split(',')][0]
foo
snippsat 661 Master Poster

How can I read from data.txt?

This is in every tutotial/book out there,so it should not be a problem.
I try to always use with open(),this is the prefered way(with statement has been in Python since 2006)
One short way.

import re
from collections import Counter

with open('your.txt') as f:
    no_punct = re.findall(r'\w+', f.read())
print Counter(no_punct)

remove punctuation marks from text file?

Without regex.

>>> from string import punctuation
>>> s = 'We@.._ love the?# pytho,..,n progr"""ammi@"ng'
>>> text = ''.join(c for c in s if c not in punctuation)
>>> text
'We love the python programming'
snippsat 661 Master Poster

IndexError: list index out of range

>>> l = [1,2]
>>> l[1]
2
>>> l[2]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: list index out of range

A simple print should tell you what is wrong print passWord.

If it split at at :,you will be able to call index 1 as shown in this example.
If not you get a IndexError.

>>> s = 'hello:world\n\r'
>>> s.split(':')
['hello', 'world\n\r']
>>> s.split(':')[1].strip()
'world'
snippsat 661 Master Poster

In environment variable Path,you should add root folder and scripts folder of python26.
http://www.windows7hacker.com/index.php/2010/05/how-to-addedit-environment-variables-in-windows-7/
This is what you add to Path
;C:\python26\;C:\python26\scripts\;
Restart.

Test it out in cmd(command line) type python.
Now running program pythnon somecode.py will use python26 and install modules with setuptools,pip will find and install to python26.
python setup.py install
pip install somepackage

snippsat 661 Master Poster

It returns, 'zip' is not recognized as an internal or external command

zip command works only on linux.
You can get it in windows by install GnuWin32 project,and to PATH in environment variables,
you need to add ;C:\%PROGRAMFILES%\GnuWin32\bin

But you shold really use module zipfile as suggsest by Grib.
zipfile is crossplatform and work on all system.

A fast rewrite of code to something like,with use of zipfile module.

import glob, os, time
import zipfile

source = r'C:\test_1\*'
target_dir = r'C:\test_2/'
target = target_dir + time.strftime('%Y%m%d') + '.zip'

f_zip = zipfile.ZipFile(target, "w")
for name in glob.glob(source):
    f_zip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)
f_zip.close()
Gribouillis commented: good help +13
snippsat 661 Master Poster

Use cx_Freeze
You should also set up Environment Variables to point to Python32.
http://www.daniweb.com/software-development/python/threads/359605/python-not-recognized
This mean that you can type python in any path in cmd(windows command line) and Python will start.

'''
my_cx_freeze.py
To run code from cmd
python my_cx_freeze.py build
Eksp from cmd:
C:\Python32\Scripts>python my_cx_freeze.py build
'''
from cx_Freeze import setup,Executable

includes = []
excludes = []
packages = []

filename = "your_code.py"
setup(
    name = 'Myapp',
    version = '0.1',
    description = 'Gui test',
    author = 'no',
    author_email = 'someting@my.org',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'includes':includes}},
    executables = [Executable(filename, base = "Win32GUI", icon = None)])
bdheeraj commented: thanks it worked +0
snippsat 661 Master Poster

urlopen() take string as argument.
So no need to use input() that return integer,use raw_input().
You should by the way never use input() in python 2.x,use int(raw_input()) for integer return.
input() in python 2.x has some safty issues,this has been fixed in python 3.

String formatting is natural way to do this in python.

>>> width = 640
>>> height = 480
>>> "http://www.placekitten.com/%s/%s" % (width,height)
'http://www.placekitten.com/640/48

New string foramtting,this is the preferred way

>>> width = 640
>>> height = 480
>>> "http://www.placekitten.com/{}/{}".format(width,height)
'http://www.placekitten.com/640/480'
snippsat 661 Master Poster

Hmm PEP-8 is gone fall in our head.

def __str__(self): return 'Name: '+self.name+', Salary: '+str(self.salary)+', Description: '+self.desc 

And not to happy with all that +

def __str__(self):
    return 'Name: {} Salary: {}  Description: {}'.format(self.name, self.salary, self.desc)
snippsat 661 Master Poster

You can use itertools permutations for this.
If this is a school task,follow woooee explanation.
And try to figure a way to get permutation without using build in tools like itertools.

Can simplify class to you dont need a method(printNum),class already has that info as you see a take out in obj.word.
And Capital letters is for class name only,work_out_combinations read PEP-8.

import itertools

class getNum:
    def __init__(self):
        self.word = input('Enter a number')

    def work_out_combinations(self):
        '''Return permutation for entred number'''
        return list(itertools.permutations(int(i) for i in self.word))

Test class.

>>> obj = getNum()
>>> obj.word
'123'
>>> obj.work_out_combinations()
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

>>> obj.work_out_combinations.__doc__
'Return permutation for entred number'
>>> help(obj.work_out_combinations)
Help on method workOutCombinations in module __main__:

workOutCombinations(self) method of __main__.getNum instance
    Return permutation for entred number
aVar++ commented: Very helpful & made a working programme, Thanks! +1
snippsat 661 Master Poster

Some more ways,i use numbers.txt as shown by Lucaci.

with open('numbers.txt') as f:
    print [i.strip() for i in f]

#['1', '2', '3', '4', '5', '6', '7', '8']

So we get a list of numbers that are strings.
To get a list with integer or float,use int() or float()

with open('numbers.txt') as f:
    print [float(i) for i in f]

#[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]

Rembere output is always strings when you read from file.
Can test with sum() and output is as expected.

with open('numbers.txt') as f:
    print sum(float(i) for i in f) #36.0
snippsat 661 Master Poster

Some repating code like Val1,Val2 is not so god.
You should make a funcion for this and send function/operator in as argument.

Maybe this help,here is how i would write this.
I use a dictionary with lambda for operators to shorten the need for 4 function,Addition(),Multiplication()....

def showoptions():
     print("1. Addition")
     print("2. Division")
     print("3. Subtraction")
     print("4. Multiplication\n")

def get_option():
    ops = {'1': lambda x, y: x + y, '4': lambda x, y: x * y,
           '2': lambda x, y: x / y, '3': lambda x, y: x - y}
    while True:
        showoptions()
        option = input("Please Make Your Selection: ")
        if option in ops:
            return ops[option]
        else:
            print("'{}' is not a valid option,Try again\n".format(option))

def calculate(operator):
    val1 = float(input("Please Enter Value 1: "))
    val2 = float(input("Please Enter Value 2: "))
    return operator(val1,val2)

def main():
    operator = get_option()
    print('Result is: {}'.format(calculate(operator)))

if __name__ == '__main__':
    main()