Reading Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no.

Slides:



Advertisements
Similar presentations
Course A201: Introduction to Programming 10/28/2010.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Dictionaries: Keeping track of pairs
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Guide to Programming with Python
Lists Introduction to Computing Science and Programming I.
CS 5 Today Today: Midterm Exam #2 M/T 11/16-17/09, in class Life in 3d? filesdictionaries David Miller ! but there is an optional, ex. cr. circuit-building.
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.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Lists CS303E: Elements of Computers and Programming.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Ionut Trestian Northwestern University
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
CIT 590 Intro to Programming Lecture 4. How are assignments evaluated Pay attention to what the HW says it is trying to teach you about ‘modular programming’
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
IS 313 Today Schedule Week 0: files dictionaries You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where we've been… Where.
EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
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.
Vocabulary Size of Moby Dick. Algorithm 1.Read the text into Python (as a huge string) 2.Split the string into words 3.Remove duplicates 4.Count the size.
Strings in Python String Methods. String methods You do not have to include the string library to use these! Since strings are objects, you use the dot.
Next Week… Quiz 2 next week: –All Python –Up to this Friday’s lecture: Expressions Console I/O Conditionals while Loops Assignment 2 (due Feb. 12) topics:
EECS 110: Lec 14: Classes and Objects
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
CS this week 4 Building classes vs. using the library hw10pr2
EECS 110: Lec 13: Dictionaries
EECS 110: Lec 17: Review for the Final Exam
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CSC 108H: Introduction to Computer Programming
Files and Dictionaries
Bryan Burlingame Halloween 2018
Files and Dictionaries
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Lesson 09: Lists Topic: Introduction to Programming, Zybook Ch 8, P4E Ch 8. Slides on website.
6. Lists Let's Learn Python and Pygame
Data Structures – 1D Lists
Ionut Trestian Northwestern University
Python Data Structures

String and Lists Dr. José M. Reyes Álamo.
Lesson 09: Lists Class Chat: Attendance: Participation
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
Lists Part 1 Taken from notes by Dr. Neil Moore
CS this week 4 Building classes vs. using the library hw10pr2
Files Handling In today’s lesson we will look at:
CSc 110, Spring 2018 Lecture 27: Lists that change size and File Output Adapted from slides by Marty Stepp and Stuart Reges.
Northwestern University
Dictionaries: Keeping track of pairs
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Python Review
IST256 : Applications Programming for Information Systems
CSE 231 Lab 6.
CSE 231 Lab 8.
Files and Dictionaries
Python Open source Many applications Python 3 jupyter notebook
Introduction to PYTHON
Presentation transcript:

Reading Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no problem…

Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no problem… opens the file and calls it f reads the whole file and calls it text text is a single string containing all the text in the file closes the file (closing Python does the same) But how to process the text from here…?

String Manupulation >>> text 'This is a file.\nLine 2\nLast line!\n' >>> print(text) This is a file. Line 2 Last line! >>> text.split() ['This', 'is', 'a', 'file.', 'Line', '2', 'Last', 'line!'] >>> text 'This is a file.\nLine 2\nLast line!\n' >>> lines = text.split('\n') >>> lines ['This is a file.', 'Line 2', 'Last line!', ''] Returns a list of the words in the string (splitting at spaces, tabs and newlines) Returns a list of the lines in the string (splitting at newlines)

Objects, objects, everywhere! >>> L = [] # create a list, L >>> dir(L) # see all of L's methods >>> help(L.sort) # I wonder… all list methods appear -- lots of them including append, index, remove, and sort >>> help(L.index) # What does this do?

List methodsString methods List methods? Will do! but there's a fundamental difference… what and why? append count extend index insert pop remove reverse sort not including list operators capitalize center count find index isalpha lower replace split strip title upper and ~10 more… >>> dir([]) help can help >>> dir('') not including string operators

Mutable vs. immutable objects Unresolved philosophical conundrum: What happens when an immutable object meets a TV remote? 'rock' vs. Lists are mutable objects. Strings are immutable objects. (So are numbers.) >>> L = [2,1,3] >>> L.sort() >>> L [1,2,3] L has changed. >>> s = 'string' >>> s.replace('st','') 'ring' >>> s 'string' returns a NEW string no return value s has NOT changed

Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… L L[0]L[1] reference 5 42

Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… You can't choose what to name data. L[0], L[1], … L L[0]L[1] reference 5 42

Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… L[1988] = 'dragon' You can't choose what to name data. You have to start at 0. L[0], L[1], … L L[0]L[1] reference 5 42 L[1989] = 'snake'

Lists vs. Dictionaries If I had a dictionary, I guess I could look up what it was! Lists are not perfect… L[1988] = 'dragon' You can't choose what to name data. You have to start at 0. Some operations can be slow for big lists … L[0], L[1], … L L[0]L[1] reference 5 42 L[1989] = 'snake' if 'dragon' in L:

Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. It's a list where the index can be any immutable-type key. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error This seems like the key to dictionaries' value…

Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. It's a list where the index can be any immutable-type key. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error creates an empty dictionary, d This seems like the key to dictionaries' value… 1988 is the key 'dragon' is the value 1989 is the key 'snake' is the value Anyone seen this before? Retrieve data as with lists… or almost !

More on dictionaries Dictionaries have lots of built-in methods: >>> d = {1988: 'dragon', 1989: 'snake'} >>> d.keys() [ 1989, 1988 ] >>> d.has_key( 1988 ) True >>> d.has_key( 1969 ) False >>> d.pop( 1988 ) 'dragon' They don't seem moronic to me! delete a key (and its value) check if a key is present get all keys

A family dictionary?

A family dictionary… T = {'abe' :['homer','herb'], 'jackie':['marge','patty','selma'], 'homer' :['hugo','bart','lisa','maggie'], 'marge' :['hugo','bart','lisa','maggie']} keys can be any immutable type values can be any type at all… T['abe'] How to get 'selma' from T ?

A functional family? def favChild( person, Tree ): """ person is a name (a string) Tree is a dictionary of children returns person's favorite child """ if Tree.has_key( person ): Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Who is favored ? Side effects ?

A functional family? def addChild( person, Tree, jr ): """ adds person's new child to Tree """ For example, >>> addChild( 'lisa', T, 'abejr' )

A challenge… def provinceChallenge( prov ): """ prov is a dictionary of Canada's provinces -- the challenge is to name them all! """ while 0 in prov.values(): guess = input("Name a province: ") if prov.has_key( guess ) == False: print('Try again...’) elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed...’) print('Phew!’) prov = { 'BC': 0, 'AB': 0, … } help?!

Change this code so that it tells you how many times you've guessed the same province… def provinceChallenge( prov ): while '0' in prov.values(): guess = input("Guess: ") if prov.has_key( guess ) == False: print('Try again...’) elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed...’) first, for real provinces then, for incorrect guesses…

Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def favGChild( person, Tree ): gChildren = [] if Tree.has_key( person ): for child in Tree[person]: if Tree.has_key( child ): gChildren += Tree[child] if gChildren == []: return 'no one' else: gChildren.sort() return gChildren[0] def favChild( person, Tree ): if Tree.has_key( person ): Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children'