snippsat 661 Master Poster

Use Python 2.7.5
The try to run code again.

Python 3.3.2 is also ok,but most of tutorial/books are still for python 2.
Most of us still use python 2,until most 3 party module is rewritten for python 3.

snippsat 661 Master Poster

Why are you using Python 2.4 wish is 8 year old?
Code works for Python 2,even if there some ugly stuff in it.

Post full Traceback.

snippsat 661 Master Poster

Download numpy for Python 3.3 here,try again.

snippsat 661 Master Poster

You are trying to install pyhook for Python 2.7,
wish you don't have installed.
Many modules work still only for python 2.x that's why most of us still you Python 2.

Pyhook works for python 3.3 you can find a version here.

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

but in any case, I never found out how to set the interpreters...
so debugging was also a pain...

Hmm interactice interpreter has always been in botton part.
http://imageshack.us/a/img197/6707/sbin.jpg

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

Most of the Design Patterns are build languages features.
We use them all the times without thinking about this,a good video about it Python Design Patterns 1

Just a couple more videos that are really good if you new to Python.
Transforming Code into Beautiful, Idiomatic Python
Python's Class Development Toolkit

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

Alternative to Gribouillis good use of itertools.

search_word = 'card 1'
with open('filename.txt') as f:
    for line in f:
        if search_word in line:
            print 'Next line after: {} is {}'.format(search_word, next(f).strip())
            print next(f).strip()

'''Output-->
Next line after: card 1 is ball
red
'''

You can you next() to jump line for line after you search for 'card 1'.

snippsat 661 Master Poster

epicSHOOTER236 i think the point is running Python(.py) from notpad++,and not do this manual stuff.
http://npppythonscript.sourceforge.net/
For windows i like much better editor that is made for Pythnon like Pyscripter or Spyder

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
>>> 'Hi! Puctuation counts as a character.'[::2]
'H!Pcuto onsa  hrce.'

Python slice notation.

'Hi! Puctuation counts as a character.'[start:stop:step]

Start and stop(deafault :) start(H) and stop(.)
If step is positve we are moving forwards starting at(H)(if the value of 'step' is ommited, it defaults to +1)

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

name = sys.argv[1] means that you most give argument from Command-line.
run.py something if you dont give argument from Commad-line you get IndexError: list index out of range
Read about sys.argv

Your code is messy.

        else: pass
    else: pass
else: pass

This is not good at all.

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
>>> import platform
>>> platform.architecture()[0]
'32bit'

py2exe-0.6.9.win32-py2.7.exe

Check that you python version and py2exe are both 32bit or both 64bit.
I keep all to 32bit in Python,and i have 64bit windows 7.

snippsat 661 Master Poster

This should work.

import csv

with open('test.csv', 'rb') as f,open('out.csv', 'wb') as f_out:
     reader = csv.reader(f)
     writer = csv.writer(f_out)
     for row in reader:
        writer.writerow((row[3], row[5]))
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

You should try to come up with some code,many just post there school task here and show no effort to solve it.
When that said,here something you can look at.

with open('people.txt') as f, open('names.txt', 'w') as f_out:
    lst = [i.split() for i in f]
    lst_diff = [x for x in lst[-1] if x in lst[-1]]
    if lst_diff in lst:
        lst.remove(lst_diff)
    f_out.write('\n'.join(i[0] for i in lst))

    """names.txt Output-->
    perter's
    john's
    """
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

As a addition to slate explanation,do a test in interactive interpreter.

The 'is' operator is not another way to type '=='.

In most cases the use of == or != is what you want.
Normal way to use is are to test if something is identical to None like a is None or b is not None.

>>> help(id)
    Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)


>>> name1 = "rahul"
>>> name2 = "rahul"
>>> id(name1)
50933056
>>> id(name2)
50933056
>>> 
>>> name1 = [1,2,3]
>>> name2 = [1,2,3]
>>> id(name1)
52135216
>>> id(name2)
50904000
snippsat 661 Master Poster

How mean vegaseat wordlist.sort(key=len) ?

Try it out with interactive interpreter.
sort() dos a inplace sort of orginal list,sorted() generate a new list so you can store it in variable.

>>> lst = ['a', 'aaaa' ,'bb', 'aa', 'aaaaaaaaaa']
>>> lst.sort(key=len)
>>> lst
['a', 'bb', 'aa', 'aaaa', 'aaaaaaaaaa']
>>> lst.sort(key=len, reverse=True)
>>> lst
['aaaaaaaaaa', 'aaaa', 'bb', 'aa', 'a']

So here it sort by lenght,but a problem bb should be behind aa.
So here as vegaseat advised.

>>> lst = ['a', 'aaaa' ,'bb', 'aa', 'aaaaaaaaaa']
>>> lst.sort()
>>> lst
['a', 'aa', 'aaaa', 'aaaaaaaaaa', 'bb']
>>> lst.sort(key=len, reverse=True)
>>> lst
['aaaaaaaaaa', 'aaaa', 'aa', 'bb', 'a']
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

Ok i am not sure about your input,so i wirte something that may be what you want.
Remember you have to use close() on fileobject when you write to file or nothing gets written.
Always use close() when open/close like this open('input', 'r')
I use with open(),then is no need to close() fileobject because it's done automatic.

'''
textfileA.txt-->
bar
world

textfileB.txt-->
foo bar hello bar
'''

with open('textfileA.txt') as file_a, open('textfileB.txt') as file_b,\
open('textfileC.txt', 'w') as file_c:
    file_a = [i.strip() for i in file_a]
    file_b = file_b.read().split()
    for index,item in enumerate(file_b):
        for word in file_a:
            if word == item:
                file_b[index] = 'error'
    file_c.write(' '.join(file_b))

'''
textfileC.txt-->
foo error hello error
'''
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

unfortunately, I have to have a lot of the mess in there for what our teacher wants. the focus of the assignment is on global variables(randint) and try/except(error handling)

No you can stucture your code better,i don't think your teacher want you to write as you do in first post.
Here is an example of try/except,as you see i make a function for it.
An game code still look clean an nice.

import random

def user_input():
    '''Function to make sure that integers are used'''
    while True:
        try:
            guess = int(input("Take a guess: "))
            return guess
        except ValueError:
            print('Only numbers as input,try again')

secret_number = random.randint(1,10)
guess = 0
while guess != secret_number:
    guess = user_input()
    if guess > secret_number:
        print ("Lower")
    elif guess < secret_number:
        print ("Higher")
print('You guessed it! The number was {}'.format(guess))
snippsat 661 Master Poster

All versions are here

snippsat 661 Master Poster

but I am rather confused

Yes that's normal when you new to programming.
Some help,you are writing more code than you need for this and it's a little messy.
Forget errohandling(try,except),function this can you do later.
Her is the basic of the game,look at code and see if it make any seense.

import random

secret_number = random.randint(1,10)
guess = 0
while guess != secret_number:
    guess = int(input("Take a guess: "))
    if guess > secret_number:
        print ("Lower")
    elif guess < secret_number:
        print ("Higher")
print('You guessed it! The number was {}'.format(guess))

You can do error checking,but don't mess code up to much.
Game code you can put in one fuction.

Here is a simple menu function that loop,you will always fall back into this menu.
Here you can start a new game or quit.
Try to type lot of mess,you see that it cacth all error with a simple else block(no try,except)
For other input types like(int,float) you may need(try,except),but dont overuse it.
Traceback in Python are very clear and not dangerous for any user.

def game():
    '''Code for game'''
    Print('You now in game function')
    input('Press enter to return to menu')    

def menu():
    while True:
        print('(1) Play guess game')
        print('(q) Quit')
        choice = input('Enter your choice: ')
        if choice == '1':
            game()
        elif choice.lower() == 'q':
            return False
        else:
            print('Not a correct choice: {} try again'.format(choice))

if __name__ == '__main__':
    menu()

"import randint" out of the function,

snippsat 661 Master Poster

The question I have now is how can I make a dictionary out of the list d with the car manufacturer as the key and a tuple containing the year and the model should be the key's value.

Something like this.

>>> lst = ['1899 Horsey Horseless', '1909 Ford Model T', '1911 Overland OctoAuto', '2003 Hummer H2', '2004 Chevy SSR']
>>> lst = [i.split(' ', 2) for i in lst]
d = {}
>>> for i in lst:
...     d[i[1]] = i[2],i[0]
...     
>>> d
{'Chevy': ('SSR', '2004'),
 'Ford': ('Model T', '1909'),
 'Horsey': ('Horseless', '1899'),
 'Hummer': ('H2', '2003'),
 'Overland': ('OctoAuto', '1911')}

One line.

 >>> dict((v[1],(v[2],v[0])) for v in lst)
{'Chevy': ('SSR', '2004'),
 'Ford': ('Model T', '1909'),
 'Horsey': ('Horseless', '1899'),
 'Hummer': ('H2', '2003'),
 'Overland': ('OctoAuto', '1911')}

If you split as pyTony suggest,you will also get two element in list.
Then you get a IndexError when try to make a dictionary.
The you can do a try,except like this.

>>> d = {}
>>> lst = ['1899 Horsey Horseless', '1909 Ford Model T', '1961 Corvair']
>>> lst = [i.split(' ', 2) for i in lst]
>>> for i in lst:
...     try:
...         d[i[1]] = i[2],i[0]
...     except IndexError:    
...         d[i[1]] = i[0]
...     
>>> d
{'Corvair': '1961',
 'Ford': ('Model T', '1909'),
 'Horsey': ('Horseless', '1899')}