Lecture # 29 Python III: Editing a Text File in Python.

Slides:



Advertisements
Similar presentations
Lecture 7 Sept 29 Goals: Chapters 5 and 6. Scripts Sequence of instructions that we may want to run can be stored in a file (known as script). by typing.
Advertisements

Chapter 5 Editing Text Files
1 Python Chapter 3 Reading strings and printing. © Samuel Marateck.
1 Using Editors Editors let you create and edit ASCII files UNIX normally includes two editors: vi and Emacs Vi and Emacs are screen editors: they display.
C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.
Word Processing. Word Processing and the WWW Differences –WWW is dynamic Variable window size Possibly non-graphical devices Leave decisions to the browser.
CHAPTER 8 CHARACTER AND STRINGS
Introduction to Unix (CA263) File Processing. Guide to UNIX Using Linux, Third Edition 2 Objectives Explain UNIX and Linux file processing Use basic file.
Lecture # 29 Python III: Client  Server. Motivation: How the Internet Works Static HTML Pages ApacheApache ApacheApache BrowserBrowser BrowserBrowser.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 8 More on Strings and Special Methods 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Return to the Word 2007 web page Lesson 2: Creating and Editing Business Letters.
07/10/ Strings ASCII& Processing Strings with the Functions - Locate (Instr), Mid, Length (Len), Char (ChrW) & ASCII (Asc)
Chapter Three The UNIX Editors. 2 Lesson A The vi Editor.
STRINGS CMSC 201 – Lab 3. Overview Objectives for today's lab:  Obtain experience using strings in Python, including looping over characters in strings.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Python for Informatics: Exploring Information
1 The EDIT Program The Edit program is a full screen text editor that allows you to: Create text files Create text files Edit an existing text files Edit.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Lecture 7 Sept 22 Goals: Chapters 5 and 6. Scripts Sequence of instructions that we may want to run can be stored in a file (known as script). by typing.
C++ PROGRAMMING: PROGRAM DESIGN INCLUDING DATA STRUCTURES, FIFTH EDITION Chapter 10: Strings and string type.
Characters. Character Data char data type – Represents one character – char literals indicated with ' '
1 CS 177 Week 11 Recitation Slides Writing out programs, Reading from the Internet and Using Modules.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
You Need an Interpreter!. Closing the GAP Thus far, we’ve been struggling to speak to computers in “their” language, maybe its time we spoke to them in.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Shell Scripting – Putting it All Together. Agenda Escaping Characters Wildcards Redirecting Output Chaining and Conditional Chaining Unnamed and Named.
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
CSC 131: Introduction to Computer Science
Main Points: - Working with strings. - Problem Solving.
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
String Processing Upsorn Praphamontripong CS 1110
CMPT 120 Topic: Python strings.
Vi Editor.
Linux 104 Training Module File Editing.
Strings Part 1 Taken from notes by Dr. Neil Moore
Engineering Innovation Center
Announcements 2nd homework is due this week Wednesday (October 18)
String Processing.
Winter 2018 CISC101 11/16/2018 CISC101 Reminders
Chapter 7 Files and Exceptions
Summary of what we learned so far
Chapter 8 More on Strings and Special Methods
Python - Strings.
Announcements 3rd homework is due this week Wednesday (March 15)
Winter 2018 CISC101 12/5/2018 CISC101 Reminders
Chapter 8 More on Strings and Special Methods
4.1 Strings ASCII & Processing Strings with the Functions
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Programming Training Main Points: - Working with strings.
Strings, Lists, and Files
15-110: Principles of Computing
Topics Introduction to File Input and Output
Bryan Burlingame 13 March 2019
Introduction to Computer Science
String Processing.
Announcements HW1 is due TODAY.
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Presentation transcript:

Lecture # 29 Python III: Editing a Text File in Python

Create a Text File: Georgie Porgie pudding and.py, Kissed the girls and made them cry When the boys came out to play, Georgie Porgie ran away.

Create a “Search & Replace” Python Program that will: Open the text file

Create a “Search & Replace” Python Program that will: Open the text file Input replacement text (name) from the keyboard

Create a “Search & Replace” Python Program that will: Open the text file Input replacement text (name) from the keyboard Search the text file to find the name “Georgie”

Create a “Search & Replace” Python Program that will: Open the text file Input replacement text (name) from the keyboard Search the text file to find the name “Georgie” Swap that name in place of “Georgie”

Create a “Search & Replace” Python Program that will: Open the text file Input replacement text (name) from the keyboard Search the text file to find the name “Georgie” Swap that name in place of “Georgie” Create and open a new file

Create a “Search & Replace” Python Program that will: Open the text file Input replacement text (name) from the keyboard Search the text file to find the name “Georgie” Swap that name in place of “Georgie” Create and open a new file Output the edited string to the new file

Create a “Search & Replace” Python Program that will: Open the text file Input replacement text (name) from the keyboard Search the text file to find the name “Georgie” Swap that name in place of “Georgie” Create and open a new file Output the edited string to the new file Close the new file

Create a “Search & Replace” Python Program that will: Open the text file: f = open(pickAFile())

Create a “Search & Replace” Python Program that will: Input replacement text (name) from the keyboard:

Create a “Search & Replace” Python Program that will: Input replacement text (name) from the keyboard: r = raw_input("Input replacement name: ”)

Create a “Search & Replace” Python Program that will: Search the text file to find the name “Georgie”: s = f.read() reads text file containing “Georgie” into string, s s.find(“Georgie”) finds “Georgie” in string, s returns index of the “G”. Georgie Porgie pudding and index …

Create a “Search & Replace” Python Program that will: In this case index = 0, for first occurrence of “Georgie.” Georgie Porgie pudding and index … In general, s.find returns index of first occurrence of substring that is found.

Create a “Search & Replace” Python Program that will: Swap that name in place of “Georgie”: let r = “Jimmy” p = “Georgie”

Create a “Search & Replace” Python Program that will: Swap that name in place of “Georgie”: let r = “Jimmy” p = “Georgie” t = r + s[s.find("Georgie",0,len(s))+len(p):len(s)] find Georgie between index 0 and len(s) skip past Georgie

Create a “Search & Replace” Python Program that will: Swap that name in place of “Georgie”: let r = “Jimmy” p = “Georgie” t = r + s[s.find("Georgie",0,len(s))+len(p):len(s)] t = Jimmy + _Porgie pudding and.py, … Georgie Porgie pudding and.py, find Georgie between index 0 and len(s) skip past Georgie

Create a “Search & Replace” Python Program that will: Since there are actually 2 occurrences of “Georgie”: Do t = r + s[s.find("Georgie",0,len(s))+len(p): s.find("Georgie",len(p),len(s))] s[n:m] references the portion of string s that we want to concatenate to r. find Georgie between index 0 and len(s)

Create a “Search & Replace” Python Program that will: Since there are actually 2 occurrences of “Georgie”: Do t = r + s[s.find("Georgie",0,len(s))+len(p): s.find("Georgie",len(p),len(s))] + r + s[s.find("Georgie",len(p),len(s)) + len(p):len(s)] get the second occurrence of Georgie find Georgie between index 0 and len(s)

Create a “Search & Replace” Python Program that will: Create and open a new (edied) file: g = open(“… put in file path here …” + r (Call file new name, Jimmy) + “.txt”,”wt”) - text extension - open for writing Borrow from f

Create a “Search & Replace” Python Program that will: Output the edited string, t, to the new file: g.write(t) g.close() And be sure to close the file

Algorithms for Basic Word Processing  Type a character Delete a character Select some characters Bold some characters Cut / Copy / Paste

Cursor Position: an index into the string Cursor = 3 Cursor=6

Typing a Character Cursor=4 Cursor = 3 Key = ‘ p ’

Typing a Character Cursor = 3 Key = ‘ p ’ For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } Text[Cursor] = Key; Cursor = Cursor+1;

Typing a Character Cursor = 3 Key = ‘ p ’ I=8 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } move character up one space Text[Cursor] = Key; Cursor = Cursor+1;

Typing a Character Cursor = 3 Key = ‘ p ’ I=7 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } move character up one space Text[Cursor] = Key; Cursor = Cursor+1;

Typing a Character Cursor = 3 Key = ‘ p ’ I=6 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } move character up one space Text[Cursor] = Key; Cursor = Cursor+1;

Typing a Character Cursor = 3 Key = ‘ p ’ I=5 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } move character up one space Text[Cursor] = Key; Cursor = Cursor+1;

Typing a Character Cursor = 3 Key = ‘ p ’ I=4 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } move character up one space Text[Cursor] = Key; Cursor = Cursor+1;

Typing a Character Cursor = 3 Key = ‘ p ’ I=3 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } Text[Cursor] = Key; add the typed character Cursor = Cursor+1;

Typing a Character Cursor = 4 Key = ‘ p ’ I=3 For ( index I starting at Text.length-1 down to Cursor) {Text[I+1]=Text[I] } Text[Cursor] = Key; Cursor = Cursor+1; move the cursor over

Algorithms for Basic Word Processing Type a character  Delete a character Select some characters Bold some characters Cut / Copy / Paste

Delete a Character Cursor = 4 Key = delete I=? For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } move a character down one space Cursor = Cursor-1; Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 4 Key = delete I=3 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } move a character down one space Cursor = Cursor-1; Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 4 Key = delete I=4 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } move a character down one space Cursor = Cursor-1; Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 4 Key = delete I=5 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } move a character down one space Cursor = Cursor-1; Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 4 Key = delete I=6 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } move a character down one space Cursor = Cursor-1; Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 4 Key = delete I=7 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } move a character down one space Cursor = Cursor-1; Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 3 Key = delete I=8 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } Cursor = Cursor-1;move the cursor over Text[Text.length-1] = “ no character ”

Delete a Character Cursor = 3 Key = delete I=8 For ( index I starting at Cursor+1 up to Text.length-1) {Text[I-1]=Text[I] } Cursor = Cursor-1; Text[Text.length-1] = “ no character ” ; blank out last character

A Helpful Function Function moveChars(Text,Start,End,Distance) {if (Distance>0) {for (index I from End down to Start ) { Text[I+Distance]=Text[I];} } Else {for (index I from Start up to End ) { Text[I+Distance]=Text[I] } }

Typing a Character Cursor = 3 Key = ‘ p ’ moveChars(text,Cursor,text.length-1, 1); Text[Cursor]=Key; Cursor=Cursor+1;

Delete a Character Cursor = 4 Key = delete I=? moveChars(text,cursor,text.length-1,-1); Cursor=Cursor-1; text[text.length -1]=no character;

Algorithms for Basic Word Processing Type a character Delete a character  Select some characters Bold some characters Cut / Copy / Paste

Selecting Characters Start = 2 End = 7

Algorithms for Basic Word Processing Type a character Delete a character Select some characters  Bold some characters Cut / Copy / Paste

Bolding Characters Start = 2 End = 7 moveChars(text,End,text.length-1,2); moveChars(text,Start,End-1,1); Text[Start]=code for start bold; Text[End+1]=code for end bold; End=End+2;

Bolding Characters Start = 2 End = 7 moveChars(text,End,text.length-1,2); -> moveChars(text,7,7,2) moveChars(text,Start,End-1,1); Text[Start]=code for start bold; Text[End+1]=code for end bold; End=End+2;

Bolding Characters Start = 2 End = 7 moveChars(text,End,text.length-1,2); moveChars(text,Start,End-1,1); -> moveChars(text,2,6,1) Text[Start]=code for start bold; Text[End+1]=code for end bold; End=End+2;

Bolding Characters Start = 2 End = 7 moveChars(text,End,text.length-1,2); moveChars(text,Start,End-1,1); Text[Start]=code for start bold; Text[End+1]=code for end bold; End=End+2;

Bolding Characters Start = 2 End = 7 moveChars(text,End,text.length-1,2); moveChars(text,Start,End-1,1); Text[Start]=code for start bold; Text[End+1]=code for end bold; End=End+2;

Bolding Characters Start = 2 End = 9 moveChars(text,End,text.length-1,2); moveChars(text,Start,End-1,1); Text[Start]=code for start bold; Text[End+1]=code for end bold; End=End+2;

Algorithms for Basic Word Processing Type a character Delete a character Select some characters Bold some characters  Cut / Copy / Paste

Cut Start = 2 End = 7 ClipBoard= For (each character C with index >= Start and < End) { copy C to the ClipBoard } moveChars(text,End,text.length-1,Start-End); Set the last (End-Start) characters in the array to “ no character ” End=Start;

Cut Start = 2 End = 7 ClipBoard= “ strin ” For (each character C with index >= Start and < End) { copy C to the ClipBoard } moveChars(text,End,text.length-1,Start-End); Set the last (End-Start) characters in the array to “ no character ” End=Start;

Cut Start = 2 End = 7 ClipBoard = “ strin ” For (each character C with index >= Start and < End) { copy C to the ClipBoard } moveChars(text,End,text.length-1,Start-End); Set the last (End-Start) characters in the array to “ no character ” End=Start;

Cut Start = 2 End = 7 ClipBoard = “ strin ” For (each character C with index >= Start and < End) { copy C to the ClipBoard } moveChars(text,End,text.length-1,Start-End); Set the last (End-Start) characters in the array to “ no character ” End=Start;

Cut Start = 2 End = 2 ClipBoard = “ strin ” For (each character C with index >= Start and < End) { copy C to the ClipBoard } moveChars(text,End,text.length-1,Start-End); Set the last (End-Start) characters in the array to “ no character ” End=Start;

Copy Start = 2 End = 7 ClipBoard = “ strin ” For (each character C with index >= Start and < End) { copy C to the ClipBoard }

Paste Start = 2 End = 2 ClipBoard = “ strin ” moveChars(text,End,text.length-1, ClipBoard.length); Copy the characters from ClipBoard into the array at index Start

Paste Start = 2 End = 2 ClipBoard = “ strin ” moveChars(text,End,text.length-1, ClipBoard.length); Copy the characters from ClipBoard into the array at index Start

Paste Start = 2 End = 2 ClipBoard = “ strin ” moveChars(text,End,text.length-1, ClipBoard.length); Copy the characters from ClipBoard into the array at index Start

More about Python

String Encodings ASCII –special characters: \n = Linefeed \r = Carriage return \t = Horizontal Tab Unicode –u”…..”

Accessing Substrings str[i] – getting the i th character in str len(str) – returns the length of the str slices –str[n:m] – str[n] through str[m-1] –str[:m] – str[0] through str[m-1] –str[n:] – str[n] through str[len(str)-1] –str[:] – str[0] through str[len(str)-1] The entire string –str[-1:] – str[len(str)-1] through str[len(str)-1] A sequence with 1 character, the last character –str[:-1] – str[0] through str[len(str)-2] Demo

String Methods String methods –capitalize() – only the first word in the string –startswith(prefix) – returns 1 or 0 –endswith(suffix) –find(str), find(str, start), find(str, start, end) returns -1 if string not found –rfind variant –upper(), lower(), swapcase() String methods –isalpha() –isdigit() –replace(string, replacement)

Importing Modules Decomposing a program into parts or modules Module is a python file –Ends in “.py” Python file contains methods, variables, and classes Forms of import –import file_name Assumes file_name ends in “.py” Must use full path name to access member of module –from file_name import * –from file_name import x, y, z –import x as y

Examples Form Letter – Program_91.py (and command line)Program_91.py changeLittle Example – Program_92.py (and command line)Program_92.py –use sample.py as first parameter findSequence – Program_93.py (and command line)Program_93.py replaceAllOccurrences – Program_94.pyProgram_94.py –use sample.py again Web Scraping – Program_95.pyProgram_95.py titleDirectory – Program_96.pyProgram_96.py –setMediaPath to MediaSources random – Program_97.pyProgram_97.py random sentences –Execution of a module from command line Program_97a.py Program_97b.py –Including a main routine import97a.py import97b.py

Built in Python Modules (The Python library) Often used modules –os, sys, random –datetime, calendar –calendar –math –zipfile – –SimpleHTTPServer Why use modules –Save work, why reinvent the wheel? –Higher quality Fewer bugs Run faster Well documented

Lists Literals –a = [1, 2, 3, 4] Access –a[i] for loops –for i in a: Concatenation –“+” operator Lists of lists –access – a[i][j] Methods –append(element) –remove(something) –sort() –reverse() –count() –split(delimeter) strings to lists of strings Functions –max(list) –min(list)

Files List of bytes Name Suffix –Type of information in file Folder or Directory Structure –Trees Trees as lists of lists of lists of … –Traversing a tree with dot notation From root –Traversing domain names students.cs.byu.edu