Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. c:\ron\mit\classes\6.006\trunk\07spring\docdist>python -i python -i Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2+3 5 >>> 3-2 1 >>> 2*4 8 >>> 2/4 0 >>> 2.0 / 4.0 0.5 >>> 5//2 2 >>> 5%2 1 >>> 2**78 302231454903657293676544L >>> _ 302231454903657293676544L >>> int("123") 123 >>> hex(_) '0x7b' >>> pow(3,1023,79) 12 >>> "abc" 'abc' >>> "abc"=='abc' True >>> """ ... abc ... """ '\nabc\n' >>> len(_) 5 >>> import string >>> help() Welcome to Python 2.5! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> modules Please wait a moment while I gather a list of all available modules... ArrayPrinter bisect mailcap struct BaseHTTPServer bsddb markupbase subprocess Bastion bz2 marshal sunau CGIHTTPServer cPickle math sunaudio Canvas cProfile md5 symbol ConfigParser cStringIO mhlib symtable Cookie calendar mimetools sys Dialog cgi mimetypes tabnanny DocXMLRPCServer cgitb mimify tarfile FFT chunk mmap telnetlib FileDialog clearcmd mmapfile tempfile FixTk cmath mmsystem test HTMLParser cmd modulefinder textwrap IPython code msilib this InterpreterExec codecs msvcrt thread InterpreterPasteInput codeop multiarray threading LinearAlgebra collections multifile time MA colorsys mutex timeit MLab commands netbios timer Matrix commctrl netrc tkColorChooser MimeWriter compileall new tkCommonDialog Numeric compiler nntplib tkFileDialog Numeric_headers contextlib nt tkFont PhysicalQInput cookielib ntpath tkMessageBox PhysicalQInteractive copy ntsecuritycon tkSimpleDialog Precision copy_reg nturl2path toaiff Queue csv numeric_formats token RNG ctypes numeric_version tokenize RandomArray curses odbc trace ScrolledText datetime opcode traceback SimpleDialog dbhash operator tty SimpleHTTPServer dbi optparse turtle SimpleXMLRPCServer dde os types SocketServer decimal os2emxpath umath StringIO difflib parser unicodedata Tix dircache path unittest Tkconstants dis pdb urllib Tkdnd distutils perfmon urllib2 Tkinter doctest pickle urlparse UserArray dumbdbm pickleshare user UserDict dummy_thread pickletools uu UserList dummy_threading pipes uuid UserString email pkgutil warnings _LWPCookieJar encodings platform wave _MozillaCookieJar envpersist popen2 weakref __builtin__ errno poplib webbrowser __future__ exceptions posixfile whichdb _ast ext_rehashdir posixpath win2kras _bisect ext_rescapture pprint win32api _bsddb filecmp profile win32clip _codecs fileinput pspersistence win32clipboard _codecs_cn fnmatch pstats win32com _codecs_hk formatter pty win32con _codecs_iso2022 fpformat py_compile win32console _codecs_jp ftplib pyclbr win32cred _codecs_kr functools pydoc win32crypt _codecs_tw gc pyexpat win32cryptcon _csv getopt pygame win32event _ctypes getpass pyreadline win32evtlog _ctypes_test gettext pythoncom win32evtlogutil _elementtree glob pywin win32file _functools gopherlib pywintypes win32gui _hashlib gzip quopri win32gui_struct _heapq hashlib random win32help _hotshot heapq ranlib win32inet _locale hmac rasutil win32inetcon _lsprof hotshot re win32job _md5 htmlentitydefs readline win32lz _msi htmllib regcheck win32net _multibytecodec httplib regutil win32netcon _numpy ibrowse repr win32pdh _random idlelib rexec win32pdhquery _sha igrid rfc822 win32pdhutil _sha256 ihooks rgbimg win32pipe _sha512 imageop rlcompleter win32print _socket imaplib robotparser win32process _sqlite3 imghdr runpy win32profile _sre imp sched win32ras _ssl imputil scipy win32rcparser _strptime inspect select win32security _struct ipipe servicemanager win32service _subprocess ipy_completers sets win32serviceutil _symtable ipy_constants sgmllib win32timezone _testcapi ipy_defaults sha win32trace _threading_local ipy_exportdb shelve win32traceutil _tkinter ipy_extutil shlex win32ts _types ipy_gnuglobal shutil win32ui _weakref ipy_p4 signal win32uiole _win32sysloader ipy_pydb site win32verstamp _winreg ipy_render smtpd win32wnet _winxptheme ipy_signals smtplib winerror afxres ipy_stock_completers sndhdr winioctlcon aifc ipy_system_conf socket winnt anydbm ipy_which sqlite3 winperf array isapi sre winsound arrayfns itertools sre_compile winxpgui astyle jobctrl sre_constants winxptheme asynchat keyword sre_parse wsgiref asyncore lapack_lite sspi xdrlib atexit ledit sspicon xml audiodev linecache stat xmllib audioop locale statvfs xmlrpclib base64 logging string xxsubtype bdb macpath stringold zipfile binascii macurl2path stringprep zipimport binhex mailbox strop zlib Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". help> string Help on module string: NAME string - A collection of string operations (most are no longer used). FILE c:\python25\lib\string.py DESCRIPTION Warning: most of the code you see here isn't normally used nowadays. Beginning with Python 1.6, many of these functions are implemented as methods on the standard string object. They used to be implemented by a built-in module called strop, but strop is now obsolete itself. Public module variables: whitespace -- a string containing all characters considered whitespace lowercase -- a string containing all characters considered lowercase letters uppercase -- a string containing all characters considered uppercase letters letters -- a string containing all characters considered letters digits -- a string containing all characters considered decimal digits hexdigits -- a string containing all characters considered hexadecimal digits octdigits -- a string containing all characters considered octal digits punctuation -- a string containing all characters considered punctuation printable -- a string containing all characters considered printable CLASSES __builtin__.object Template class Template(__builtin__.object) | A string class for supporting $-substitutions. | | Methods defined here: | | __init__(self, template) | | safe_substitute(self, *args, **kws) | | substitute(self, *args, **kws) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __metaclass__ = | | | delimiter = '$' | | idpattern = '[_a-z][_a-z0-9]*' | | pattern = <_sre.SRE_Pattern object at 0x00AEA810> FUNCTIONS atof(s) atof(s) -> float Return the floating point number represented by the string s. atoi(s, base=10) atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted. atol(s, base=10) atol(s [,base]) -> long Return the long integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted. A trailing L or l is not accepted, unless base is 0. capitalize(s) capitalize(s) -> string Return a copy of the string s with only its first character capitalized. capwords(s, sep=None) capwords(s, [sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. Note that this replaces runs of whitespace characters by a single space. center(s, width, *args) center(s, width[, fillchar]) -> string Return a center version of s, in a field of the specified width. padded with spaces as needed. The string is never truncated. If specified the fillchar is used instead of spaces. count(s, *args) count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string s[start:end]. Optional arguments start and end are interpreted as in slice notation. expandtabs(s, tabsize=8) expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8). find(s, *args) find(s, sub [,start [,end]]) -> in Return the lowest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. index(s, *args) index(s, sub [,start [,end]]) -> int Like find but raises ValueError when the substring is not found. join(words, sep=' ') join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous) joinfields = join(words, sep=' ') join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous) ljust(s, width, *args) ljust(s, width[, fillchar]) -> string Return a left-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. If specified the fillchar is used instead of spaces. lower(s) lower(s) -> string Return a copy of the string s converted to lowercase. lstrip(s, chars=None) lstrip(s [,chars]) -> string Return a copy of the string s with leading whitespace removed. If chars is given and not None, remove characters in chars instead. maketrans(...) maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length. replace(s, old, new, maxsplit=-1) replace (str, old, new[, maxsplit]) -> string Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, only the first maxsplit occurrences are replaced. rfind(s, *args) rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. rindex(s, *args) rindex(s, sub [,start [,end]]) -> int Like rfind but raises ValueError when the substring is not found. rjust(s, width, *args) rjust(s, width[, fillchar]) -> string Return a right-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. If specified the fillchar is used instead of spaces. rsplit(s, sep=None, maxsplit=-1) rsplit(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. rstrip(s, chars=None) rstrip(s [,chars]) -> string Return a copy of the string s with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. split(s, sep=None, maxsplit=-1) split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified or is None, any whitespace string is a separator. (split and splitfields are synonymous) splitfields = split(s, sep=None, maxsplit=-1) split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified or is None, any whitespace string is a separator. (split and splitfields are synonymous) strip(s, chars=None) strip(s [,chars]) -> string Return a copy of the string s with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping. swapcase(s) swapcase(s) -> string Return a copy of the string s with upper case characters converted to lowercase and vice versa. translate(s, table, deletions='') translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. The deletions argument is not allowed for Unicode strings. upper(s) upper(s) -> string Return a copy of the string s converted to uppercase. zfill(x, width) zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. DATA ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' hexdigits = '0123456789abcdefABCDEF' letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' lowercase = 'abcdefghijklmnopqrstuvwxyz' octdigits = '01234567' printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU... punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' whitespace = '\t\n\x0b\x0c\r ' help> quit You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. >>> "XY"*3 'XYXYXY' >>> A = string.letters >>> A 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> A[3] 'd' >>> A[3:6] 'def' >>> A[3:] 'defghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> A[-1] 'Z' >>> A[:7] 'abcdefg' >>> A[:] 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> B = string.digits >>> B '0123456789' >>> A+B 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' >>> C = 'abCD' >>> string.upper(C) 'ABCD' >>> string.lower(C) 'abcd' >>> S = "Mary had a little lamb" >>> string.split(S) ['Mary', 'had', 'a', 'little', 'lamb'] >>> S = "abracadabra" >>> T = string.maketrans("ab","XX") >>> S.translate(T) 'XXrXcXdXXrX' >>> __ Traceback (most recent call last): File "", line 1, in NameError: name '__' is not defined >>> "A bc D".split() ['A', 'bc', 'D'] >>> "ab" < "b" True >>> len("abc") 3 >>> S 'abracadabra' >>> S[0] = 'b' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment >>> 'b' + S[1:] 'bbracadabra' >>> S 'abracadabra' >>> S = 'abc' >>> T = 'ab' >>> T = 'abc' >>> S == T True >>> id(S) 23086240 >>> id(T) 23086240 >>> S is string False >>> S 'abc' >>> type(S) >>> S is type("abc") False >>> "abc" is "abc" True >>> type(S) == type("abc") True >>> type(S) is type("abc") True >>> [] [] >>> [2,3] [2, 3] >>> ["ab",4] ['ab', 4] >>> [[1,0],[0,1]] [[1, 0], [0, 1]] >>> _[0][1] 0 >>> [0]*7 [0, 0, 0, 0, 0, 0, 0] >>> range(4) [0, 1, 2, 3] >>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,100,17) [1, 18, 35, 52, 69, 86] >>> L = [i**2 for i in range(7)] >>> L [0, 1, 4, 9, 16, 25, 36] >>> len(L) 7 >>> L[2] 4 >>> L[-1] 36 >>> L[-3] 16 >>> L[:] [0, 1, 4, 9, 16, 25, 36] >>> L.pop() 36 >>> L [0, 1, 4, 9, 16, 25] >>> L.append(36) >>> L [0, 1, 4, 9, 16, 25, 36] >>> L.extend([49,64]) >>> L [0, 1, 4, 9, 16, 25, 36, 49, 64] >>> L.reverse() >>> L [64, 49, 36, 25, 16, 9, 4, 1, 0] >>> L.sort() >>> L [0, 1, 4, 9, 16, 25, 36, 49, 64] >>> sorted(L) [0, 1, 4, 9, 16, 25, 36, 49, 64] >>> L.reverse() >>> L [64, 49, 36, 25, 16, 9, 4, 1, 0] >>> sorted(L) [0, 1, 4, 9, 16, 25, 36, 49, 64] >>> L [64, 49, 36, 25, 16, 9, 4, 1, 0] >>> del L[0] >>> L [49, 36, 25, 16, 9, 4, 1, 0] >>> M = range(4) >>> L [49, 36, 25, 16, 9, 4, 1, 0] >>> M [0, 1, 2, 3] >>> L+M [49, 36, 25, 16, 9, 4, 1, 0, 0, 1, 2, 3] >>> list("abc") ['a', 'b', 'c'] >>> string.join(_,"") 'abc' >>> import math >>> math.sqrt(6) 2.4494897427831779 >>> map(math.sqrt,range(7)) [0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.2360679774997898, 2.4494897427831779] >>> [mathsqrt(i) for i in range(7)] Traceback (most recent call last): File "", line 1, in NameError: name 'mathsqrt' is not defined >>> [math.sqrt(i) for i in range(7)] [0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.2360679774997898, 2.4494897427831779] >>> L [49, 36, 25, 16, 9, 4, 1, 0] >>> L[0]= 5 >>> L [5, 36, 25, 16, 9, 4, 1, 0] >>> L = (1,2,3,5) >>> type(L) >>> list(L) [1, 2, 3, 5] >>> tuple(_) (1, 2, 3, 5) >>> T = _ >>> T (1, 2, 3, 5) >>> T[0] = 5 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> ["ab",3] < ["b",2] True >>> ["ab",3] < ["ab",2] False >>> for i in range(5): ... print i ... 0 1 2 3 4 >>> for i in range(5): ... print i File "", line 2 print i ^ IndentationError: expected an indented block ----------------- BREAK TO CREATE FOO.PY, WHICH LOOKS LIKE THIS: --------- def gcd(a,b): if b == 0: return a return gcd(b, a%b) -------------------------------------------------------------------------- >>> import foo >>> foo.gcd(15,25) 5 >>> from foo import * >>> gcd(2,4) 2 >>> from docdist3 import * >>> L = read_file("t2.bobsey.txt ") >>> L[:5] ['The Project Gutenberg eBook, The Bobbsey Twins on Blueberry Island, by\n', 'Laura Lee Hope\n', '\n', '\n', 'This eBook is for the use of anyone anywhere at no cost and with\n'] >>> W = get_words_from_line_list(L) >>> W[:7] ['the', 'project', 'gutenberg', 'ebook', 'the', 'bobbsey', 'twins'] >>> F = count_frequency(W) >>> F[:7] [['the', 2509], ['project', 88], ['gutenberg', 100], ['ebook', 10], ['bobbsey', 339], ['twins', 158], ['on', 369]] >>> D = {} >>> D {} >>> D['ab'] = 2 >>> D {'ab': 2} >>> D['cde'] = 4 >>> D {'cde': 4, 'ab': 2} >>> D['the'] = 45 >>> D['the'] 45 >>> D['as'] Traceback (most recent call last): File "", line 1, in KeyError: 'as' >>> D.has_key("as") False >>> D.has_key("the") True >>> "the" in D True >>> 45 in D False >>> D.keys() ['cde', 'the', 'ab'] >>> D.items() [('cde', 4), ('the', 45), ('ab', 2)] >>> from docdist4 import * >>> F = count_frequency(W) >>> F.items()[:7] Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'items' >>> F[:7] [('raining', 4), ('pardon', 1), ('limited', 5), ('hats', 1), ('yellow', 11), ('hitch', 5), ('four', 11)] >>>