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

Yes Python only find code in PYTHONPATH.
There are some solutions,you can move your "modules subfolder" to a folder in PYTHONPATH.
Usually all Python modules/code get placed in C:\Python26\Lib\site-packages

You can append to PYTHONPATH.

import sys
sys.path.append(r'C:\path\to\module')

The only bad ting with this solution is that is not permanent.

To permanently add to PYTHONPATH,you can do this.
Search for sitecustomize.py,if you dont find it make it in C:\Python26\Lib\site-packages
In this sitecustomize.py file add this.

#sitecustomize.py
import sys
sys.path.append(r'C:\path\to\module')

Restart Python.
Now see if your C:\path\to\module are in print sys.path.

An other option is just to make .pth file in site-packages folder.
In that file just add C:\path\to\module

snippsat 661 Master Poster

I added the semi-colen before the python path that I need the program to access, the program is not finding the path in the system variable ?

I think you are mixing the understanding of environment variable and PYTHONPATH.
Environment variable you set so Windows find the Python version you use.
PYTHONPATH is the path Python search for Python code/programs.

To se where Python search you can do this.

>>> import sys
>>> print sys.path
#Here you get a list of all folder python search for code(PYTHONPATH)
#If you have a .py in one of this folders Python will find it

I don't understand what I should test out in a python command

No you should test python command out in command line for OS called cmd
Here how it look for me when i type in python in cmd.

Microsoft Windows [Versjon 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Med enerett.

C:\Users\Tom>cd\

C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

If environment variable is set up correct you can type python anywhere in cmd(command line) and Python will start.
So to sum it up Environment variable is so that windows can find Python.
PYTHONPATH is where Python search for Python code(.py).

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

I was welcomed with a lot of negative feedback, due to "Hmm PEP-8 falling on my head", thus my next move would be to offering you some exemplified links to help you figure that out. So here it is:

Sorry it's was more about how your code was indented,your help was very good.
So write more stuff like that,and don't take criticism to serisous PEP-8 it's just as suggestion how Python code shold look.
I myself do not follow all in PEP-8,and i have gotten criticism for this before.

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
>>> #Python2.x
>>> key = 5
>>> print "module {0}".format(key)
module 5

>>> #Python 3.x
>>> print("module {0}".format(key))
module 5
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

Test print will show you files to be removed.
If ok remove comment(#) from #os.remove(files)
Remember never use C:\
Use raw string r'C:\' or C:\\ or C:/

import os, glob, time, sys

def file_remove(folder, exp_date, ext):
    '''Remove files older than than set exp_date'''
    for files in glob.glob('{}\*.{}'.format(folder, ext)):
        lastmod_date = time.localtime(os.stat(files)[8])
        ex_date = time.strptime(exp_date, '%d-%m-%Y')
        if  ex_date > lastmod_date:
            try:
                #Test print
                print 'Removing {} {}'.format(files, time.strftime("<Older than %d-%m-%Y>",ex_date))
                #os.remove(files)
            except OSError:
                print 'Could not remove {}'.format(files)

if __name__ == '__main__':
    folder = r'C:\test'
    #Expiration date format DD-MM-YYYY
    exp_date = '07-02-2013'
    #File extension to search for
    ext = 'txt'
    file_remove(folder, exp_date, ext)
snippsat 661 Master Poster

All txt files in blah.

import glob

for files in glob.glob(r'C:\blah\blah\*.txt'):
    print files

Run all files through os.stat
What you need is st_mtime,nr 8.

Now you can use time(import time),make a time object for 14_days back.
Make a time object from os.stat(files)[8]call it lastmod_date.
Compare 14_days > lastmod_date use os.remove(files) on files it give back.

snippsat 661 Master Poster

So are you happy with this code,do you have a question?
Just to post some code without any question is not helping anyone,it's just irritating.

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()
snippsat 661 Master Poster

Some ways,but it can get ugly.
Code in my first post may be the way to go if you want that output.

Vegaseat way is't ok to use '\n'join() method.

>>> print '\n'.join(["%d %s" % pair for pair in enumerate(names)])
0 Google
1 Apple
2 Microsoft

Iterate over list comprehension and print result.

>>> lst = [pair for pair in enumerate(names)]
>>> for i in lst:
        print i[0], i[1]

0 Google
1 Apple
2 Microsoft

Not so nice but it work,maybe there is nicer ways to do this?

>>> print '\n'.join([' '.join([str(index), item]) for index, item in enumerate(names)])
0 Google
1 Apple
2 Microsoft

Or.

>>> print '\n'.join([str(pair[0]) + ' ' + pair[1] for pair in enumerate(names)])    
0 Google
1 Apple
2 Microsoft
snippsat 661 Master Poster

Ok here is list comprehension way.

>>> [(index, item) for index, item in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
Or.
>>> [pair for pair in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
snippsat 661 Master Poster
>>> names = ['Google', 'Apple', 'Microsoft']
>>> for index,item in enumerate(names):
        print index,item

0 Google
1 Apple
2 Microsoft
snippsat 661 Master Poster

You should almost never use global varible in function,it's ugly.
Function should take argument an return values out.
Some code you can look at.

#Ver_1
def foo():
    bar = "Just a string"
    return bar

print foo() #Just a string

#Ver_2
def foo(global_bar):
    bar = "Just a string and from ouside {}".format(global_bar)
    return bar

global_bar = "global Variable"
print foo(global_bar) #Just a string and from ouside global Variable

#Ver_3
def foo(global_bar="global Variable"):
    '''Here i use default argument'''
    bar = "Just a string and from default arg {}".format(global_bar)
    return bar

print foo() #Just a string and from default arg global Variable
snippsat 661 Master Poster

If the data endered ends with one of the 3 extensions, I would like it to be returned and the snes emulator to be opened.

Your logic dos not make sense to me.
If user input game.smc,should all files that has a smc extensions be found?
Explain your self better.

You never use data returned by os.listdir('/SNES/SNESRoms').
data return are all files in /SNES/SNESRoms,but if you never use it what's the point?

What i mean is this,here i use data to do something.

for data in os.listdir('/SNES/SNESRoms'):
    print data #all files in /SNES/SNESRoms that you never use
    if data.endswith(extensions):
        print data #all files that ends with extension definde before in extensions.
snippsat 661 Master Poster

However, I don't use punctuation because it breaks any contractions in the text/word list

No problem just use signs in your code,then it will keep contractions.

text = "My!. @car%& can't be good"
print ''.join(c for c in text if c not in "!@#$%^&*().[],{}<>?") #My car can't be good
snippsat 661 Master Poster

You are removing element for nonwordlist in a loop,that's why it's blow up.
A rule is can be,never delete something from or add something to the list you are iterating over.

You can solve this in diffrent ways,the easiest for you now can be to make a copy of list.
for word in nonwordlist[:]:

A couple more tips.
Remove punctuation:

from string import punctuation

text = 'My!.= @car%&'
print ''.join(c for c in text if c not in punctuation) #My car

Read from file to a list,a little shorter than vega code.

with open("Encontract.txt") as fin:
    contrwords = [i.strip() for i in fin]
snippsat 661 Master Poster

Hi some problems with function inputs(),you need to retun values out and assign it to one or two variabels in main.
This should do it.

def inputs():
    '''Get input from user'''
    weight = float(input('Enter weight in pounds: '))
    height = float(input('Enter height in inches: '))
    return weight, height

def hw_to_bmi(weight, height):
    '''Calculate bmi'''
    bmi = (weight / (height * height)) * 703
    print('Your BMI is %.2f' % bmi)

def main():
    weight,height = inputs()
    hw_to_bmi(weight,height)
    print(hw_to_bmi.__doc__)
    help(inputs)

main()
snippsat 661 Master Poster

Ok the only think i can think of,is that the there is a problem with your test.txt.
As you say there is no problem if you writing in one url.

You can test with repr() to see all that test.txt is outputing.
So here google and sol url adress work,and i get <urlopen error no host given> on Python adress because of missing / this is when test run it in my code over.

for site in open('test.txt'):
    print repr(site)

"""Output--> repr
'http://www.google.com/videohp\n'
'http:/www.python.org/\n'
'http://www.sol.no/\n'
'\n'
"""

"""Output--> from code over
http://www.google.com/videohp
<urlopen error no host given>
http://www.sol.no/
unknown url type:
"""
snippsat 661 Master Poster

For fun one with regex,but i guess this is a school task?

import re

string = 'alpha 111 bravo 222 alpha somethingA end, 333 bravo somethingB end 444 alpha 555 bravo'
pattern = re.compile(r'(alpha|bravo)(\s\w+\s)(end)')
for match in pattern.finditer(string):
    print match.group(2).strip()

"""Output-->
somethingA
somethingB
"""
snippsat 661 Master Poster

Do some exception handling to figure out what's going on.

import urllib2

for site in open('test.txt'):
    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    try:
        home = opener.open(site)
        print home.geturl()
    except Exception as error:
        print error

So here it will print all ok url's,if one is bad it will print <urlopen error no host given>
instead of that adress.

snippsat 661 Master Poster

There is no problem in my code chriswelborn.
The point was to get @inuasha to check his test.txt for missing /.
When i teset,i did change http:// to http:/ to get samme error as he has.

snippsat 661 Master Poster

This code work for me.

test.txt
*http://www.google.com/videohp
*http://www.python.org/

---

import urllib2

for site in open('test.txt'):
    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    home = opener.open(site)
    print home.geturl()

Check url's in test.txt,if i delete one /.
I get URLError: <urlopen error no host given>

snippsat 661 Master Poster

test.txt is a file,so you have to open it for read open('test.txt'):

snippsat 661 Master Poster

Would it be easier if the "file1.txt", file2.txt", etc were .csv files? Would this helping the coding? Thanks

No it would not help,the challenge is the same if you need to multiply vaules from difference files.
The only difference is \n or ,
Look at this,if use spilt() on both the output list is the same.

>>> s = '''111.11
    222.22'''
>>> s
'111.11\n222.22'
>>> s.split()
['111.11', '222.22']

>>> csv = '111.11, 222.22'
>>> csv
'111.11, 222.22'
>>> csv.split(',')
['111.11', ' 222.22']

>>> sum(float(i) for i in s.split())
333.33    
>>> sum(float(i) for i in csv.split(','))
333.33
snippsat 661 Master Poster

You can try this,glob will iterate over all your file..txt
I use fileinput module to open all files.
Then calulate two sum based on enumerate even/odd.

import fileinput
from glob import glob

sum_file = open("SumFile.csv", "w")
total = 0.0
total_1 = 0.0
fnames = glob('file*.txt')
for numb,line in enumerate(fileinput.input(fnames)):
    if numb % 2 == 0:
        total += float(line.strip())
    else:
        total_1 += float(line.strip())
sum_file.write('%6.20f,\n%6.20f,\n' % (total, total_1))
sum_file.close()
snippsat 661 Master Poster

You don't need to include re it's a python build in module and cxFreeze will find it.
If you want to include moduls you also need to modify setup.

Here is a test i did with regex,as you see i include nothing.
If it work re_test.exe will output ['fast', 'friendly']

''''
Put "my_cx_freeze.py" and "re_test.py"(your script) in same folder.
Run it from command line(cmd) or terminal linux,navigate to folder with script.
Then type python my_cx_freeze.py build
'''

#my_cx_freeze.py
from cx_Freeze import setup,Executable

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

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

---

#re_test
import re

match = re.findall(r'\bf.*?\b', 'a fast and friendly dog')
print(match)
raw_input('Press enter to exit')
#input('Press enter to exit') #for python 3 use this
snippsat 661 Master Poster

Something like this look better,and 'do' is not used in Python.

s = 'ABsomething'
if s.startswith(('AB','CC','EF','US')):
    print '{}subroutine'.format(s[:2])
else:
    print 'Substring not found'
snippsat 661 Master Poster
>>> flowers = ['rose', 'bougainvillea', 'yucca', 'marigold', 'daylilly', 'lilly of the valley']
>>> thorny = []
>>> #First element in flowers list
>>> flowers[0]
'rose'

>>> #append first element to thorny list
>>> thorny.append(flowers[0])
>>> thorny
['rose']
>>> thorny.append(flowers[1])
>>> thorny
['rose', 'bougainvillea']
>>> thorny.append(flowers[2])
>>> thorny
['rose', 'bougainvillea', 'yucca']

>>> #Remember you can use help or look at Python doc
>>> help(thorny.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end

>>> dir(thorny) 
#All function/methods you can use on list,look away from magic methods start with __.
snippsat 661 Master Poster

Some good example over,one more.
Running it interactive can help.
I keep function out from interactive environment,then it's eaiser to keep indentation.

def foo(x):
    print 'foo got called with argument', x
    def wrapped(y):
        return x * y
    return wrapped

Run it.

>>> foo
<function foo at 0x02AA1DB0>
>>> #Memory location of uncalled foo  

>>> foo(4)
foo got called with argument 4
<function wrapped at 0x029955B0>
>>> #We see foo get called and we get memory location of uncalled wrapped

>>> foo(4)(5)
foo got called with argument 4
20
>>> #Both function is called

>>> #So store it in a varible
>>> bar = foo(4)
foo got called with argument 4
>>> #So to get the same as over foo(4)(5)
>>> bar(5)
20
snippsat 661 Master Poster

Some hint that should help you.

>>> lst = [1,2,3,4,5,6]
>>> lst[:3]
[1, 2, 3]

#Assign to list thorny
>>> help(lst.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end
#Or
>>> help(lst.extend)
Help on built-in function extend:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable

>>> #Concatenation of lists?
>>> ['Hello'] + ['world']
['Hello', 'world']
snippsat 661 Master Poster
>>> lst = [[1,2], [3,4]]
>>> lst
[[1, 2], [3, 4]]
>>> sum(lst, [])
[1, 2, 3, 4]

When use sum() on the outer list and set second argument to an empty list [],default is 0.
Python will concatenate the inner lists,producing a flattened list.
so on the inner list.

>>> [1,2] + [3,4]
[1, 2, 3, 4]
snippsat 661 Master Poster

Yes here is list comprehension much better looking,than my (for fun) functional programming style soultion.

snippsat 661 Master Poster

The functional programming way with map() is short and fine for this.
In Python are list comprehension used much and in many cases more prefered than a functional style.

def to_numbers(str_list):
    return [int(i) for i in str_list]

lst = ['1', '2']
print to_numbers(lst)

If you wonder why i have changed to small letter and use _,look at PEP-8.

snippsat 661 Master Poster

Ok thanks.
If it's a school task deliver this for fun,and ask your teacher to explain it.

>>> sum(map(lambda x: str.split(x, ','), lst), [])
['10015', ' John', ' Smith', ' 2', ' 3.01', '10334', ' Jane', ' Roberts', ' 4', ' 3.81', '10208', ' Patrick', ' Green', ' 1', ' 3.95']
snippsat 661 Master Poster
lst = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95'] 
>>> new_lst = []    
>>> for data in lst:
        for item in data.split(','):
            new_lst.append(item)

>>> print new_lst
['10015', ' John', ' Smith', ' 2', ' 3.01', '10334', ' Jane', ' Roberts', ' 4', ' 3.81', '10208', ' Patrick', ' Green', ' 1', ' 3.95']
snippsat 661 Master Poster

and create a list of this form

That's not a list,if you want only those item in a new list.

lst = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95']
>>> lst[:2]
['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81']

To get the output you show.

>>> new_lst = lst[:2]
>>> for data in new_lst:     
        for item in data.split(', '):
            print item

10015
John
Smith
2
3.01
10334
Jane
Roberts
4
3.81
snippsat 661 Master Poster

As posted by @dashing.adamhughes there are made a lot of stuff that can help you with this,another eksp is pyfasta

How to get the start and end position of a particular pattern

You can use re.finditer for this.

>>> import re
>>> s = '11ATGC1111ATGC11111ATGC'
>>> p = 'ATGC'
>>> [m.start() for m in re.finditer(p, s)]
[2, 10, 19]
>>> #To also find end postion
>>> [(m.start(),m.end()) for m in re.finditer(p, s)]
[(2, 6), (10, 14), (19, 23)]
snippsat 661 Master Poster

I think doc explain it ok os.getenv() and sys.path

A simplified explation of some use of those could be.
If i want to import a Python module made by me or other,i have to make sure it is in sys.path so Python can find it.

In my windows environment variables i have add ;C:\python27\;C:\python27\scripts;
This mean that i type just Python in cmd(command line) to start Python.
os.getenv('path') give me back all path that's in my Windows environment variables(path).

snippsat 661 Master Poster

mac_address live alone in global space.
If you want it in your class you have pass it in as a instance variable or a agrument for for method resolve.

>>> from foo import Mac
>>> b = Mac(mac_address)
>>> b.resolve()
{'000000': 'xerox0', '000001': 'xerox1', '000002': 'xerox2'}

Or

class Mac:
    def __init__(self,hexmac):
        self.hexmac = hexmac

    def resolve(self, mac_address):
        return self.hexmac, mac_address

mac_address = { \
'000000':'xerox0', \
'000001':'xerox1', \
'000002':'xerox2', \
}

Use class.

>>> b = Mac('123')
>>> b.resolve(mac_address)
('123', {'000000': 'xerox0', '000001': 'xerox1', '000002': 'xerox2'})
snippsat 661 Master Poster

but i wanted to learn re module..

Start with something simpler.
An example could be something like this.
Match phonenumber with +.

>>> import re
>>> s = '"taruna","  09015561619","  +918968391049",,"tarunthegreat43@gmail.com",,,'
>>> re.findall(r'\+\d+', s)
['+918968391049']

So \+ macth +.
+ alone has a spesiell mening(Matches 1 or more of the preceeding token)
\d Matches any digit character (0-9)
And last + so we get whole number.

Email adress.
\w+ Matches any word character
Then mactch @,then a new \w+.\w+
So will this work?

>>> s = '"taruna","  09015561619","  +918968391049",,"tarunthegreat43@gmail.com",,,'
>>> re.findall(r'\w+@\w+.\w+', s)
['tarunthegreat43@gmail.com']

Read python doc
There are many online tools that can help with regex.
http://www.gskinner.com/RegExr/
http://osteele.com/tools/rework/
http://regexlib.com/?AspxAutoDetectCookieSupport=1
http://rubular.com/

snippsat 661 Master Poster

A space in in gdata youtube search is %20
So if you search for car bmw,then it should look like this car%20bmw
Here is one way of do it.

>>> word = 'car bmw'
>>> word = word.split()
>>> word
['car', 'bmw']
>>> space = '%20'
>>> word = space.join(word)
>>> word
'car%20bmw'
>>> url = 'max-results=01&vq=' + word
>>> url
'max-results=01&vq=car%20bmw'

This will work for longere sentence or a single word.

>>> word = 'car'
>>> word = word.split()
>>> word
['car']
>>> word = space.join(word)
>>> word
'car'
>>> url = 'max-results=01&vq=' + word
>>> url
'max-results=01&vq=car'

You should not do error handling(try,except) in that way.
Try to make it clear what error you will catch,and do not put other stuff if try,except block.
example:

#Python 3  
from urllib import request,error

try:
    url = request.urlopen('http://google.com111').read()
    print(url)
except error.URLError:
    print('No url by that name found')

Here it is clear that we only catch error if a url adress is wrong or site is down.
If you later need error check like append stuff to a list,you write a own error chek for that.

snippsat 661 Master Poster

When you iterate over with csv.reader(ins) you get a list output.
['3.2323232312']

>>> map(int, ['3.2323232312'])
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.2323232312'

>>> map(float, ['3.2323232312'])
[3.2323232312]

Even if you use float you just get 3 separate list,and sum() would not work.
If you want to add up those numbers,here one way.

with open('e1.csv') as ins:
    print sum(float(i) for i in ins) #14.1092143611

If you have more problem post an example of how E1.csv look,not just a column.
You dont have to post whole file,but some lines that are complete and desired output.

snippsat 661 Master Poster

One more stone turned:

Collections is good,and i think we should also mention the star when it's come to counting stuff collections.Counter.

>>> from collections import Counter
>>> import random
>>> Counter(random.randint(1,10) for i in range(100))[3]
8
>>> Counter(random.randint(1,10) for i in range(100))[3]
9

Some more fun with Counter.

>>> from collections import Counter
>>> lst = [3,3,3,3,9,9,1,3,3,5]
>>> counter = Counter(lst)
>>> counter[3]
6
>>> counter.most_common(2)
[(3, 6), (9, 2)]
>>> counter.most_common(1)
[(3, 6)]


>>> fruits = ['Apple', 'Apple', 'Pear', 'Orange', 'Banana', 'Apple', 'Banana']
>>> fruit_count = Counter(fruits)
>>> fruit_count
Counter({'Apple': 3, 'Banana': 2, 'Orange': 1, 'Pear': 1})
>>> fruit_count.most_common(1)
[('Apple', 3)]
>>> fruit_count.most_common(2)
[('Apple', 3), ('Banana', 2)]
>>> fruit_count['Apple']
3


>>> import itertools
>>> nested_lst = [[1,3,3],[1,2,3]]
>>> nested_counter = Counter(itertools.chain(*nested_lst))
>>> nested_counter[3]
3
>>> nested_counter
Counter({3: 3, 1: 2, 2: 1})
>>> nested_counter.most_common(1)
[(3, 3)]
Gribouillis commented: nice +13