*** Strona 251-252 ***************************************************************

newList = myList[:]

newDict = {}
for key in myDict.keys():
    newDict[key] = myDict[key]

newDict = myDict.copy()

for key in otherDict.keys():
    oneDict[key] = otherDict[key]

def mergeWithoutOverlap(oneDict, otherDict):
    newDict = oneDict.copy()
    for key in otherDict.keys():
        if key in oneDict.keys():
            raise ValueError, "te dwa slowniki wspoldziela klucze!"
        newDict[key] = otherDict[key]
    return newDict

def mergeWithOverlap(oneDict, otherDict):
    newDict = oneDict.copy()
    for key in otherDict.keys():
        if key in oneDict.keys():
            newDict[key] = oneDict[key], otherDict[key]
        else:
            newDict[key] = otherDict[key]
    return newDict

phoneBook1 = {'michael': '555-1212', 'mark': '554-1121', 'emily': '556-0091'}
phoneBook2 = {'latoya': '555-1255', 'emily': '667-1234'}


*** Strona 253 *******************************************************************

>>> import copy
>>> listOne = [{"name": "Willie", "city": "Providence, RI"}, 1, "tomato", 3.0]
>>> listTwo = listOne[:]                   # or listTwo=copy.copy(listOne)
>>> listThree = copy.deepcopy(listOne)
>>> listOne.append("kid")
>>> listOne[0]["city"] = "San Francisco, CA"
>>> print listOne, listTwo, listThree
[{'name': 'Willie', 'city': 'San Francisco, CA'}, 1, 'tomato', 3.0, 'kid']
[{'name': 'Willie', 'city': 'San Francisco, CA'}, 1, 'tomato', 3.0]
[{'name': 'Willie', 'city': 'Providence, RI'}, 1, 'tomato', 3.0]


*** Strona 254 *******************************************************************

listCopy = list(myTuple)
listCopy.sort()
for item in listCopy:
    print item                  # lub cokolwiek, co ma by robione

keys = myDict.keys()            # zwraca nieposortowan list
                                # kluczy w sowniku
keys.sort()
for key in keys:                # drukuje pary klucz, warto
    print key, myDict[key]      # posortowane wedug klucza

>>> def caseIndependentSort(cokolwiek, inne):
...    cokolwiek, inne = string.lower(cokolwiek), string.lower(inne)
...    return cmp(cokolwiek, inne)
...
>>> testList = ['jest', 'A', 'posortowana', 'Lista']
>>> testList.sort()
>>> print testList
['A', 'Lista', 'jest', 'posortowana']
>>> testList.sort(caseIndependentSort)
>>> print testList
['A', 'jest', 'Lista', 'posortowana']


while myList:                 # zapobiega zaptlaniu, gdy myList jest pusta
    element = random.choice(myList)
    myList.remove(element)
    print element,


*** Strona 255-256 ***************************************************************

class Stack:
    def __init__(self, data):
        self._data = list(data)
    def push(self, item):
        self._data.append(item)
    def pop(self):
        item = self._data[-1]
        del self._data[-1]
        return item

>>> rzeczyDoZrobienia = Stack(['napisac list', 'wyprosic kogos', 'umyc dziecko'])
>>> rzeczyDoZrobienia.push('umyc naczynia')
>>> print rzeczyDoZrobienia.pop()
umyc naczynia
>>> print rzeczyDoZrobienia.pop()
umyc dziecko


# import klasy UserList z moduu UserList
from UserList import UserList

# klasa podrzdna klasy UserList
class Stack(UserList):
    push = UserList.append
    def pop(self):
        item = self[-1]         # uywa __getitem__
        del self[-1]
        return item

>>> rzeczyDoZrobienia = Stack(['napisac list', 'wyprosic kogos', 'umyc dziecko'])
>>> print rzeczyDoZrobienia          # odziedziczone z UserList
['napisac list', 'wyprosic kogos', 'umyc dziecko']
>>> rzeczyDoZrobienia.pop()
'umyc dziecko'
>>> rzeczyDoZrobienia.push('zmienic olej')
>>> for chore in rzeczyDoZrobienia: # mona wykona take iteracj
...    print chore                  # poniewa "for ..in .." uywa __getitem__
...
napisac list
wyprosic kogos
zmienic olej


*** Strona 257-259 ***************************************************************

import sys
data = sys.stdin.readlines()
print "Counted", len(data), "lines."

% cat countlines.py | python countlines.py
Counted 3 lines.

C:\> type countlines.py | python countlines.py
Counted 3 lines.


# Znajdowanie wszystkich wierszy, ktre rozpoczynaj si od znaku #

import sys
for line in sys.stdin.readlines():
    if line[0] == '#':
        print line,


# Wyodrbnianie czwartej kolumny pliku (kolumny s zdefiniowane za pomoc spacji)

import sys, string
for line in sys.stdin.readlines():
    words = string.split(line)
    if len(words) >= 4:
        print words[3]

# lub...

    try:
        print words[3]
    except IndexError:              # nie ma wystarczajcej liczby sw
        pass


# Wyodrbnianie czwartej kolumny pliku (kolumny s oddzielone dwukropkami) i zamiana liter na mae

import sys, string
for line in sys.stdin.readlines():
    words = string.split(line, ':')
    if len(words) >= 4:
        print string.lower(words[3])

# Wydruk pierwszych 10 wierszy, ostatnich 10 wierszy i kadego parzystego wiersza

import sys, string
lines = sys.stdin.readlines()
sys.stdout.writelines(lines[:10])           # pierwsze 10 wierszy
sys.stdout.writelines(lines[-10:])          # ostatnie 10 wierszy
for lineIndex in range(0, len(lines), 2):   # otrzymujemy 0, 2, 4, ...
    sys.stdout.write(lines[lineIndex])      # mamy indeksowany wiersz

# Zliczanie powtrze sowa "Python" w pliku

import string
text = open(fname).read()
print string.count(text, 'Python')


# Zamiana listy kolumn na list wierszy

import sys, string
lines = sys.stdin.readlines()
wordlists = []
for line in lines:
    words = string.split(line)
    wordlists.append(words)
for row in range(len(wordlists[0])):
    for col in range(len(wordlists)):
        print wordlists[col][row] + '\t',
    print


*** Strona 259-261 ***************************************************************

# odczyt znak po znaku
while 1:
    next = sys.stdin.read(1)     # odczyt acucha jednoznakowego
    if not next:                 # lub pustego acucha przy EOF
        break
    Przetwarza znak 'next'

# odczyt wiersz po wierszu
while 1:
    next = sys.stdin.readline()  # odczyt acucha jednowierszowego
    if not next:                 # albo pustego acucha przy EOF
        break
    Przetwarza wiersz 'next'


% python myScript.py input1.txt input2.txt input3.txt output.txt

import sys
inputfilenames, outputfilename = sys.argv[1:-1], sys.argv[-1]
for inputfilename in inputfilenames:
    inputfile = open(inputfilename, "r")
    do_something_with_input(inputfile)
outputfile = open(outputfilename, "w")
write_results(outputfile)

def do_something_with_input(inputfile):
    for line in inputfile.readlines()
        process(line)


import fileinput
for line in fileinput.input():
    process(line)


import fileinput, sys, string
# pobiera pierwszy argument z sys.argv i przypisuje go do searchterm (warunku wyszukiwania)
searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
for line in fileinput.input():
   num_matches = string.count(line, searchterm)
   if num_matches:                # niezerowe zliczenie - byo dopasowanie
       print "found '%s' %d times in %s on line %d." % (searchterm, num_matches,
           fileinput.filename(), fileinput.filelineno())


*** Strona 261-265 *******************************************************************

import os, string
if len(sys.argv) == 1:                    # jeli brak nazw plikw
    filenames = os.listdir(os.curdir)     # uywa aktualnego katalogu
else:                                     # w przeciwnym wypadku nazw plikw
    filenames = sys.argv[1:]              # podanych w wierszu polece
for filename in filenames:
    if ' ' in filename:
        newfilename = string.replace(filename, ' ', '_')
        print "Renaming", filename, "to", newfilename, "..."
        os.rename(filename, newfilename)


import sys, glob, operator
print sys.argv[1:]
sys.argv = reduce(operator.add, map(glob.glob, sys.argv))
print sys.argv[1:]

/usr/python/book$ python showglob.py *.py
['countlines.py', 'mygrep.py', 'retest.py', 'showglob.py', 'testglob.py']
['countlines.py', 'mygrep.py', 'retest.py', 'showglob.py', 'testglob.py']

C:\python\book> python showglob.py *.py
['*.py']
['countlines.py', 'mygrep.py', 'retest.py', 'showglob.py', 'testglob.py']


>>> numbers = range(30)
>>> def even(x):
...    return x % 2 == 0
...
>>> print numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
>>> print filter(even, numbers)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]


import string
words = string.split(open('myfile.txt').read()) # pobieramy wszystkie sowa

def at_least_ten(word):
    return len(word) >= 10

longwords = filter(at_least_ten, words)


lines = open('myfile.txt').readlines()
lines = filter(None, lines)              # pusty acuch jest faszywy


*** Strona 265 *******************************************************************

# odczyt pliku wejciowego
inputFile = open('input.txt', 'r')

import tempfile
# tworzy plik tymczasowy
tempFile = tempfile.TemporaryFile()                   # nie trzeba nawet
first_process(input = inputFile, output = tempFile)   # zna nazwy pliku

# tworzy kocowy plik wyjciowy
outputFile = open('output.txt', 'w')
second_process(input = tempFile, output = outputFile)


formletter = """Drogi %s,\nPisze, aby zasugerowac, ze ..."""     # itd.
myDatabase = [('Bill Clinton', 'bill@whitehouse.gov.us'),
              ('Bill Gates', 'bill@microsoft.com'),
              ('Bob', 'bob@subgenius.org')]
for name, email in myDatabase:
    specificLetter = formletter % name
    tempfilename = tempfile.mktemp()
    file = open(tempfilename, 'w')
    file.write(specificLetter)
    file.close()
    os.system('/usr/bin/mail %(email)s -s "Urgent!" < %(tempfilename)s' % vars())
    os.remove(tempfilename)


*** Strona 266-268 ***************************************************************

#!/usr/bin/env python
import sys, string
entries = {}

for line in open(sys.argv[1], 'r').readlines():
    left, right = string.split(line)
    try:
        entries[right].append(left)              # rozszerza list
    except KeyError:
        entries[right] = [left]                  # widziane po raz pierwszy

for (right, lefts) in entries.items():
    print "%04d '%s'\tpozycje => %s" % (len(lefts), right, lefts)



# lub
if entries.has_key(right):         # czy ju jest w sowniku?
    entries[right].append(left)    # dodaje do listy aktualnych wartoci
else:
    entries[right] = [left]        # inicjuje list wartoci klucza


% cat data.txt
1       raz
2       raz
3       dwa
7       trzy
8       dwa
10      raz
14      trzy
19      trzy
20      trzy
30      trzy

% python collector1.py data.txt
0003 'raz'      pozycje => ['1', '2', '10']
0005 'trzy'     pozycje => ['7', '14', '19', '20', '30']
0002 'dwa'      pozycje => ['3', '8']



#!/usr/bin/env python
import sys, string

def collect(file):
    entries = {}
    for line in file.readlines():
        left, right = string.split(line)
        try:
            entries[right].append(left)       # rozszerza list
        except KeyError:
            entries[right] = [left]           # widziane pierwszy raz
    return entries

if __name__ == "__main__":                    # gdy uruchamiane jako skrypt
    if len(sys.argv) == 1:
        result = collect(sys.stdin)           # odczyt ze strumienia stdin
    else:
        result = collect(open(sys.argv[1], 'r'))  # odczyt z nazwy pliku
    for (right, lefts) in result.items():
        print "%04d '%s'\tpozycje => %s" % (len(lefts), right, lefts)


# uruchamianie jak skrypt
% collector2.py < data.txt
w tym miejscu jest wywietlany wynik

# uycie w jakim innym skadniku (lub interakcyjnie)
from collector2 import collector
result = collect(open("mielonka.txt", "r"))
...w tym miejscu przetwarzanie wyniku


>>> from collector2 import collect
>>> from StringIO import StringIO
>>>
>>> str = StringIO("1 one\n2 one\n3 two")
>>> result = collect(str)               # skanuje opakowany acuch
>>> print result                        # {'raz':['1', '2'], 'dwa':['3']}


*** Strona 269-271 ***************************************************************

for datafname in ['data.001', 'data.002', 'data.003']:
    for parametr1 in range(1, 10):
        os.system("analizujDane -in %(datafname)s -param1 %(parametr1)d" % vars())


#!/usr/bin/env python
# znajduje pliki, szuka znakw tabulacji

import string, os
cmd = 'find . -name "*.py" -print'          # find - narzdzie uniksowe

for file in os.popen(cmd).readlines():      # uruchamia polecenie find
    num = 1
    name = file[:-1]                        # usuwa '\n'
    for line in open(name).readlines():     # skanuje plik
        pos = string.find(line, "\t")
        if pos >= 0:
            print name, num, pos            # zgasza znaleziony tabulator
            print '....', line[:-1]         # [:-1] usuwa kocowe \n
            print '....', ' '*pos + '*', '\n'
    num = num+1


C:\python\book-examples> python findtabs.py
./szczesliwepaluszki.py 2 0
.... for i in range(10):
.... *

./szczesliwepaluszki.py 3 0
....       print "oops..."
.... *

./szczesliwepaluszki.py 5 5
.... print   "marny styl"
....      *


import sys
if sys.platform == "win32":         # w wersji dla Windows
    try:
        import win32pipe
        popen = win32pipe.popen
    except ImportError:
        raise ImportError, "The win32pipe module could not be found"
else:                               # w przeciwnym wypadku dla POSIX
    import os
    popen = os.popen
... i dalej stosowa popen, ignorujc z bogoci rodzaj platformy


*** Strona 271 *******************************************************************

# plik get_temperature.py
import urllib, urlparse, string, time

def get_temperature(country, state, city):
    url = urlparse.urljoin('http://www.weather.com/weather/cities/',
                           string.lower(country)+'_' + \
                           string.lower(state) + '_' + \
                           string.replace(string.lower(city), ' ',
                                          '_') + '.html')
    data = urllib.urlopen(url).read()
    start = string.index(data, 'current temp: ') + len('current temp: ')
    stop = string.index(data, '&deg;C', start-1)
    temp = int(data[start:stop])
    localtime = time.asctime(time.localtime(time.time()))
    print ("Data: %(localtime)s, temperatura w %(city)s, " +\
           "%(state)s %country)s: %(temp)s C.") % vars()

get_temperature('FR', '', 'Paris')
get_temperature('US', 'RI', 'Providence')
get_temperature('US', 'CA', 'San Francisco')


~/book:> python get_temperature.py
Data: Wed Nov 25 16:22:25 1998, temperatura w Paris, FR: 14 C.
Data: Wed Nov 25 16:22:30 1998, temperatura w Providence, RI US: 14 C.
Data: Wed Nov 25 16:22:35 1998, temperatura w San Francisco, CA US: 28 C.


*** Strona 273 *******************************************************************

>>> from poplib import *
>>> server = POP3('mailserver.mielonka.org')
>>> print server.getwelcome()
+OK QUALCOMM Pop server derived from UCB (version 2.1.4-R3) at mielonka starting.
>>> server.user('da')
'+OK Password required for da.'
>>> server.pass_('nigdyniezgadniesz')
'+OK da has 153 message(s) (458167 octets).'
>>> header, msg, octets = server.retr(152)  # pobieramy ostatnie wiadomoci
>>> import string
>>> print string.join(msg[:3], '\n')        # spjrzmy na pierwsze 3 wiersze
Return-Path: <jim@bigbad.com>
received: from gator.bigbad.com by mailserver.mielonka.org (4.1/SMI-4.1)
        id AA29605; Wed, 25 Nov 98 15:59:24 PST


*** Strona 273-274 ***************************************************************

# plik interest.py

trace = 1     # czy drukowa kady rok?

def calc(principal, interest, years):
    for y in range(years):
        principal = principal * (1.00 + (interest / 100.0))
        if trace: print y+1, '=> %.2f' % principal
    return principal

% python
>>> from interest import calc
>>> calc(65000, 5.5, 10)
1 => 68575.00
2 => 72346.63
3 => 76325.69
4 => 80523.60
5 => 84952.40
6 => 89624.78
7 => 94554.15
8 => 99754.62
9 => 105241.13
10 => 111029.39
111029.389793

>>> import interest
>>> interest.trace = 0
>>> calc(65000, 5.5, 10)
111029.389793


def calc(principal, interest, years):
    interest = interest / 100.0
    for y in range(years):
        earnings = principal * interest
        principal = principal + earnings
        if trace: print y+1, '(+%d)' % earnings, '=> %.2f' % principal
    return principal

>>> interest.trace = 1
>>> calc(65000, 5.5, 10)
1 (+3575) => 68575.00
2 (+3771) => 72346.63
3 (+3979) => 76325.69
4 (+4197) => 80523.60
5 (+4428) => 84952.40
6 (+4672) => 89624.78
7 (+4929) => 94554.15
8 (+5200) => 99754.62
9 (+5486) => 10541.13
10 (+5788) => 111029.39
111029.389793


*** Strona 275 *******************************************************************

#!/usr/bin/env python
# znajduje wolny modem do zestawienia poczenia

import glob, os, string
LOCKS = "var/spool/locks/"

locked = [0] * 10
for lockname in glob.glob(LOCKS + "LCK*modem*"): # znajduje zajte modemy
    print "Zablokowany:", lockname
    locked[string.atoi(lockname[-1])] = 1        # 0..9 na kocu nazwy

print 'free: ',
for i in range(10):                              # raport, wybieranie numeru
    if not locked[i]: print i,
print

for i in range(10):
    if not locked[i]:
        if raw_input("Proba %d? " % i) == 'y':
            os.system("kermit -m hayes -l /dev/modem%d -b 19200 -S" % i)
            if raw_input("Dalej? ") != 'y': break


*** Strona 277 *******************************************************************

# plik rolo.py

#!/usr/bin/env python
# Interakcyjny kolonotatnik

import string, sys, pickle, cmd

class Rolodex(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)              # inicjacja podstawowej klasy
        self.prompt = "Monty's Friends: "   # modyfikacja znaku zachty
        self.people = {}                    # na pocztku nikogo nie znamy

    def help_add(self):
        print "Adds an entry (specify a name)"
    def do_add(self, name):
        if name == "": name = raw_input("Enter Name: ")
        phone = raw_input("Enter Phone Number for "+ name+": ")
        self.people[name] = phone           # dodaje nr telefonu do nazwy

    def help_find(self):
        print "Find an entry (specify a name)"
    def do_find(self, name):
        if name == "": name = raw_input("Enter Name: ")
        if self.people.has_key(name):
            print "The number for %s is %s. " % (name, self.people[name])
        else:
            print "We have no record for %s. " % (name,)

    def help_list(self):
        print "Prints the contents of the directory"
    def do_list(self, line):
        names = self.people.keys()           # klucze s nazwami
        if names == []: return               # jeli brak nazw, to koniec
        names.sort()                         # chcemy mie to wg alfabetu
        print '='*41
        for name in names:
            print string.rjust(name, 20), ":", string.ljust(self.people[name], 20)
        print '='*41

    def help_EOF(self):
        print "Quits the program"
    def do_EOF(self, line):
        sys.exit()
    def help_save(self):
        print "save the current state of affairs"
    def do_save(self, filename):
        if filename == "": filename = raw_input("Enter filename: ")
        saveFile = open(filename, 'w')
        pickle.dump(self.people, saveFile)

    def help_load(self):
        print "load a directory"
    def do_load(self, filename):
        if filename == "": filename  = raw_input("Enter filename: ")
        saveFile = open(filename, 'r')
        self.people = pickle.load(saveFile)  #zauwamy, e to zastpi
                                    # dowolny istniejcy katalog z osobami

if __name__ == '__main__':          # oto w jaki sposb modu moe by
    rolo = Rolodex()                # importowany take przez inne programy
    rolo.cmdloop()


% python rolo.py
Monty's Friends: help

Documented commands (type help <topic>):
========================================
EOF   add   find   list   load
save

Undocumented commands:
======================
help



***kod do wicze znajduje si w katalogu "rozwiazania"***