文稿教案成果asrpt_第1页
文稿教案成果asrpt_第2页
文稿教案成果asrpt_第3页
文稿教案成果asrpt_第4页
文稿教案成果asrpt_第5页
免费预览已结束,剩余26页可下载查看

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Lesson content:String ProcessingFile Input and OutputExample: Parsing a FileManipulating ProgramsWorkshop 4: Parsing FilesWorkshop 5: Input and Output with the Shelve ModuleLesson 3: Manipulating Strings and Files3 hoursString Processing (1/9)String formattingThe modulo operator (%) is used to produ

2、ce a formatted string given a format string and a collection of objects contained in a tuple or a dictionary.The basic form: % The RHS is converted to strings according to the % codes on the left.General target form:%(key_name)flagswidth.precisionconversion_code- left justify+ numeric sign0 zero fil

3、lSTRING: maximum number of characters to be printedFLOAT: # digits on right of decimal pointINT: minimum number of digitsString Processing (2/9)String formatting conversion codesCharacterOutput Formatd, IDecimal or long integeruUnsigned or long integeroOctal or long integerxHexadecimal or long integ

4、erXUpper case HexadecimalfFloat -n.nnneFloat -n.nnne+nnEFloat -n.nnnE+nng, GIf exp x = 1; y = 2 The sum of %d + %d = %d % (x, y, x+y)The sum of 1 + 2 = 3 x = 1; y = 2 The sum of + x + + + y + = + (x+y)The sum of 1 + 2 = 3 %(n)d %(x)s % n:1,x:spam1 spamUsing back-quote: Python objects can also be con

5、verted to strings by using the back-quote character but this is considered by many Python users to be bad style. It is equivalent to using repr().Using a dictionary (hint: often convenient to use globals()Using a tupleString Processing (4/9)More string formatting examplesIf in doubt about the conver

6、sion code, use %s. Python will convert the object to its string representation using str(). %s weighs %5.2f pounds % (Eric, 67)Eric weighs 67.00 pounds %s weighs %s pounds % (Eric, 67)Eric weighs 67 poundsYou may use string % dictionary substitution with variable names as format specifiers. For exam

7、ple: d = name: Eric, number: 67 %(name)s weighs %(number)5.2f pounds % dEric weighs 67.00 poundsUsing the format() methodThe format() method uses curly braces () instead of % menu=SPAM,eggs,sausage,SPAM#using position of the argument for formatting I dont want any 0!.format(menu0)I dont want any SPA

8、M#Using indices for formatting Lovely 00! Wonderful 03!.format(menu)Lovely SPAM! Wonderful SPAM!#Using list elements as arguments 0, 1, 2, and 3.format(*menu)SPAM, eggs, sausage, and SPAMString Processing (5/9)String processing modulesThere are library modules available for string processingstringVe

9、ry useful string manipulation constants and functions. For routine tasks functionality provided in string module is sufficient.reInterface for performing regular-expression pattern matching. Useful module for advanced parsing.PyparseThird party module provides capability for defining your own gramma

10、r advanced parsing. unicodedata Provides access to Unicode character database Python has extremely powerful third-party modules for advanced language parsing String Processing (6/9)String moduleMost routinely required string processing methods are available in the string processing module dir(string

11、)Formatter, Template, _TemplateMetaclass, _builtins_, _doc_, _file_, _name_, _package_, _float, _idmap, _idmapL, _int, _long, _multimap, _re, ascii_letters, ascii_lowercase, ascii_uppercase, atof, atof_error, atoi, atoi_error, atol, atol_error, capitalize, capwords, center, count, digits, expandtabs

12、, find, hexdigits, index, index_error, join, joinfields, letters, ljust, lower, lowercase, lstrip, maketrans, octdigits, printable, punctuation, replace, rfind, rindex, rjust, rsplit, rstrip, split, splitfields, strip, swapcase, translate, upper, uppercase, whitespace, zfillMost of the above methods

13、 are inbuilt with python string types. test = *element, type=c3d8i test.upper()*ELEMENT,TYPE=C3D8IString Processing (7/9)String module (contd)It has some common string processing methods like split(), find(), replace (), join(), etc.line = *Element,Type = c3d8I, elset=AllElements # Code to extract e

14、lement Typeif line.upper().find(C3D8I)=0: lines = line.split(,) for l in lines: if l.upper().find(TYPE)=0: elType = l.split(=)-1print Element Type, elTypeString Processing (8/9)String Module Example# Replace C3D8I elements with C3D8Rif line.upper().find(C3D8I)=0: line=line.upper().replace(C3D8I,C3D8

15、R)print line ,lineString Processing (9/9)Using a string objectimport sys # to access command line argumentsdef isAnagram(string1, string2): Return True if string1 is an anagram of string2. Returns False if not an anagram if len(string1) != len(string2): return False for c in string1: if string1.coun

16、t(c) != string2.count(c): return False else: return Trueif isAnagram(sys.argv1, sys.argv2): print sys.argv1, is an anagram of, sys.argv2else: print sys.argv1, is not an anagram of, sys.argv2Input and Output (1/10)Common built-in file object methodsMethodDescription f.read(n)Read at most n bytes f.re

17、adline(n)Read a single line, up to n characters or entire line f.readlines()Read all lines, return a list f.write(s)Write string s f.writelines(l)Write all strings in list l f.flush()Flush the output buffer f.close()Close the file object f.tell()Return the current file pointer f.seek(offset, where)S

18、eek to a new file position f.truncate(size)Truncate to at most size bytesInput and Output (2/10)File modesMode arguments for open(name , mode)r text mode readw text mode writea text mode write appendrb binary mode readwb binary mode writew+, r+, a+ open with update (allows both reading and writing)I

19、n Python, opening files in text mode will always map to/from a single new line character terminating each line.If you need to see raw binary data, use binary mode. Binary designation is optional for UNIX but required for Windows. Should be included if concerned about portability (i.e., prevent auto

20、map from occurring).Input and Output (3/10)Reading from filesf = open(“test.inp”,”r”)#Read all the lines and place them as a listlines = f.readlines() for line in lines: print linef.close()Writing to filesf = open(“test.txt”,”a”)lines = lines.append(“*Step,Static”)lines.append(“0.1,1”)lines.append(“

21、*End step”)f.writelines(lines)f.close()#Note file opened in append mode to avoid overwriting. Input and Output (4/10)Example: Using a File Type Object# open a file for reading, and print it outf = open(fileManipulation.txt)text = f.readlines()for line in text: print line:-1# reverse the order of the

22、 lines and save ittext.reverse()f = open(temp.txt, w)f.write(Reversed filen)for line in text: f.write(line)f.close()# now print the new fileprint open(temp.txt).read()Input and Output (5/10)Input/output redirectionThree streams of data exist as file objects when Python startsStandard Input sys.stdin

23、Standard Output sys.stdoutStandard Error sys.stderrThese data streams may be redirected. For example: x = open(log, a) sys.stdout = x print test 2+2 x.flush() sys.stdout = sys._stdout_ x.close()Files in Python are always buffered.Here we have redirected to a file object. We can redirect to other obj

24、ects such as arguments to a class instance.Reassign when done.Input and Output (6/10)Input/output redirection (contd)Can redirect output from print statement. For example: x = open(log, a) print x, testThis is similar to previous example, but no need to do the reassign.Input and Output (7/10)Modules

25、 for persistence or picklingImagine having theability to preserve your data structures, that is any arrays, dictionaries, objects, etc. in a file and retrieve them in a different program or session. This concept is referred to as pickling of objectsMore formal definition: Python is able to convert a

26、lmost any data structure into a serialized byte stream. This process is called pickling.Storing this information in a file makes it persistent across Python program executions.Pickling provides an effective approach for storing and accessing complex data structures.Limitation: Code objects and syste

27、m resources (like files or sockets) cannot be pickled.Example: The .cae and .odb files are examples of pickled Abaqus data structures. The Abaqus Object model is preserved and stored in a file to be retrieved later in a different session.Input and Output (8/10)Modules for persistence (contd)The foll

28、owing library modules provide functionality for persistence:pickle - basic but powerful algorithm for “pickling” (aka, serializing, marshalling or flattening) nearly all arbitrary Python objects. cPickle - Reimplementation of the pickle algorithm in C, which is up to 1000 times faster.shelve - Simpl

29、e interface for pickling and unpickling objects on DBM-style database files (uses cPickle if available). shelve is a very powerful easy to use module and can greatly simplify file input/output and data persistence. Input and Output (9/10)Modules for persistence (contd)shelvePickles Python objects in

30、to files that appear like dictionariesReturns a shelf object that permits basic dictionary operations.Provides access without reading the entire shelf object into memoryExample: import shelve elements = shelve.open(elementData) elements1 = (1,2,3,4) elements2 = (2,3,4,5) elements3 = (3,4,5,6) elemen

31、ts.close() elements = shelve.open(elementData) elements2(2, 3, 4, 5)Input and Output (10/10)File tools in the os moduleA distinct set of file processing functions are also available in the os moduleThe os module file tools are lower-level and more complex than the built-in file object methods and sh

32、ould only be used for special file processing needs such as pipes.The os module has sub-modules, such as os.path, used for common file operations (exists, isfile, isdir, etc.).Example: Parsing a File (1/4)Example: Plotting external XY data in Abaqus/ViewerRead the corresponding data file and make an

33、 XY plot in Abaqus/Viewer Data file For details, see the script called scr_xyplot.py in the demos directory.Example: Parsing a File (2/4)Example (contd)XY plot in Abaqus/ViewerExample: Parsing a File (3/4)Example (contd)from visualization import XYData, USER_DEFINEDdef plotExternalData(fileName):# E

34、xtract the data from the filefile = open(fileName)lines = file.readlines() # split the first line using comma delimiter# Extract header information pxy = lines0.split(,) pxy = x.strip() for x in pxy plotName, xAxisTitle, yAxisTitle = pxydata = for line in lines1: # eval converts string data sets int

35、o tuples data.append(eval(line) Example: Parsing a File (4/4)Example (contd) # Create an XY Plot of the data xyData = session.XYData(plotName, data, fileName) curve = session.Curve(xyData) xyPlot = session.XYPlot(plotName) chart = xyPlot.charts.values()0 chart.setValues(curvesToPlot=(plotName, ) cha

36、rt.axes10.axisData.setValues(useSystemTitle=False, title=xAxisTitle) chart.axes20.axisData.setValues(useSystemTitle=False, title=yAxisTitle) # Display the XY Plot in the current viewport vp = session.viewportssession.currentViewportName vp.setValues(displayedObject=xyPlot) if _name_ = _main_: plotEx

37、ternalData(scr_xyplot.dat) Manipulating Programs (1/5)Executing Python codeBuilt-in functions are available for creating, manipulating, and calling Python code.ImportExecutes code in a module and returns a module objectexec some-code in globaldict , localdictExecutes code (string, file, or compiled

38、code object) in the optionally specified global and local namespaceseval(expression , globaldict , localdict)Executes an expression (string or compiled code object)execfile(filename)Executes code in filename. It reads the file unconditionally and does not create a new module. compile(string, filenam

39、e, kind)Compiles a string into a code objectapply(function, args, , keywords)Executes a function on a tuple of argumentsManipulating Programs (2/5)Executing Python code (contd)eval()Evaluates an expressionWill not execute a statementExample: eval(1+2)3 eval(a=1+2)Traceback (most recent call last): F

40、ile , line 1, in ?TypeError: eval() takes at least 1 argument (0 given)Manipulating Programs (3/5)Executing Python code (contd)execExecutes a set of statementsWhen called, Python parses the code. This can be expensive. Use compile to improve processing efficiencyExample: code = x = 1+2; y = 0 x = 100; y = 100 exec code x,y(3, 0) x = 100; y = 100 c = compile(code, , exec) exec c x,y(3, 0)compiled code objects differ from function objects in that they dont contain a refe

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论