'''lecture_22_strings_template.py Demonstrate string properties and reading from and writing to a file by reading in and manipulating Chapter 1 of Alice in Wonderland, stored in a text file. Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' '''Reading text from a file''' # Our goal: load in from text from a file to work with in Python (Chapter 1 of Alice In Wonderland). # Process of loading text from file into a string called "reading text from a file" # theFile = open('alice_chapter_1.txt', 'r') # firstLineStr = theFile.readline() # theFile.close() # Make file object and read in one line. # print('First line:', firstLineStr) # Then read TWO lines. # File object keeps track of which lines you have already read in so when you call readline() the # second time, it remembers that you already read the first line (so won't read 1st line twice). # theFile = open('alice_chapter_1.txt', 'r') # firstLineStr = theFile.readline() # secondLineStr = theFile.readline() # theFile.close() # print('First line:', firstLineStr) # print('Second line:', secondLineStr) # To read in entire chapter: automate with loop. We don't know how many lines the line has # Can use the empty string '' as loop sentinel: What readline() returns when we reach end of file. aliceList = [] theFile = open('alice_chapter_1.txt', 'r') currentLineStr = theFile.readline() while currentLineStr != '': # print(currentLineStr) aliceList.append(currentLineStr) currentLineStr = theFile.readline() theFile.close() # Print out first few items of list (first few lines of file) # print(aliceList[:4]) '''Escape sequences''' # What are the \n things doing at the end of each string in the list? We don't see them in file! # \n is an ESCAPE SEQUENCE, a "special code" in the string, in this case to mean new line. # Example: print out 1st line. # abc = "a\n\n\nb\n\n\nc" # print(abc) # print(aliceList[0]) # print('Alices Adventures in Wonderland\n') # print('See the new line above!') # We can use them in our own strings too! # Example: Print a string variable with new lines. # # Text: 'Haikus are easy. But sometimes they dont make sense. Refrigerator.' # haiku = 'Haikus are easy.\nBut sometimes they dont make sense.\nRefrigerator.' # print(haiku) # Print function automatically tacks on \n to string we print (otherwise multiple print statements # would bunch text up on same line!). # Example: Print lines of haiku separately. # print('Haikus are easy.') # print('But sometimes they dont make sense.') # print('Refrigerator') # Print allows us to turn this off by setting keyword argument end='' (empty string): # print('Haikus are easy.', end='') # print('But sometimes they dont make sense.', end='') # print('Refrigerator', end='') # Tabs: \t # haiku = 'Haikus are easy.\tBut sometimes they dont make sense.\tRefrigerator.' # print(haiku) # Apostrophes or quotes in strings: \' or \" # Example: Missing quote in haiku # haiku = 'Haikus are easy.\nBut sometimes they don\'t make sense.\nRefrigerator.' # print(haiku) # Show how mixed quotation symbols also work (recent versions of Python only) # haiku = "Haikus are easy.\nBut sometimes they don't make sense.\nRefrigerator." # print(haiku) '''Length''' # Example: How many characters are in the 1st line of Alice in Wonderland? # print(aliceList[:2]) # testExample = 'a bc\n' # print(len(testExample)) # ...but this includes the new line character! How can we get rid of it? # print(aliceList[0]) # print(aliceList[1]) # Option 1) Slice a string: treat string like list of characters # Example: What is the length of the new line character? # Accessing single characters # We can also use the "list indexing approach" to extract single characters or ranges (substrings) # myStr = 'abc' # print(myStr[1:]) # Example: Extract substring: "Alice" from 1st line firstLine = aliceList[0] # print(firstLine) # Print Alice # print(firstLine[:5]) # Print out 1st line starting with Adventures... # print(firstLine[8:]) # The string without the new line # print(firstLine[:-1]) # print(len(firstLine)) # print(len(firstLine[:-1])) # Option 2) Strip string method # print(firstLine) # print(firstLine.strip()) # print(len(firstLine)) # print(len(firstLine.strip())) '''Looping through strings''' # We can loop thru strings, not just range and lists: # Example: Print every character of 1st line of Alice on separate line # for char in firstLine: # print(char) '''String operators''' # Concatenation: + operator with two strings # Example: Concatenate 1st two lines of Alice # firstTwo = aliceList[0] + aliceList[1] # print(firstTwo) # What if we wanted the two on the same line? # firstTwo = aliceList[0].strip() + '. ' + aliceList[1].strip() # print(firstTwo) # Example: Use concatenation to build up single BIG string of the file aliceBigString = '' aliceFile = open('alice_chapter_1.txt', 'r') currLine = aliceFile.readline() while currLine != '': aliceBigString = aliceBigString + currLine currLine = aliceFile.readline() aliceFile.close() # print(aliceBigString) '''Important string methods: Join and split''' # 1) Join: list of strings -> one string # What if we wanted to take the list of lines and make one big string out of it? # Example: How many characters are in entire chapter? # chapterString = ''.join(aliceList) # print('Number of characters in whole chapter (using join):', len(chapterString)) # print('Number of characters in whole chapter (reading from file via string concatenation):', len(aliceBigString)) # Smaller example: 1st 3 lines of alice # listOfFirstThreeLines = aliceList[:3] # print(aliceList[:3]) # first3 = ''.join(listOfFirstThreeLines) # print(first3) # Example: Adding periods (or any string) between first 3 lines, adding new line back between lines # first3 = '...'.join(aliceList[:3]) # first3 = '!!!!!!'.join(aliceList[:3]) # first3 = '-HI-'.join(aliceList[:3]) # print(first3) # 2) Split: one string -> list of strings # Example: extract words from 1st line of Alice # print(firstLine) # firstLineSplit = firstLine.split(' ') # print(firstLineSplit) # Example: Take big single string of Alice and split it up into a list of separate lines like before lines = aliceBigString.split('\n') # print(lines) '''Writing to a text file''' # Let's make a new text file and write the first two lines of Alice to it. # fileObject = open('alice_output.txt', 'w') # fileObject.write(lines[0]) # fileObject.close() # fileObject = open('alice_output.txt', 'w') # fileObject.write(lines[0]) # fileObject.write(lines[1]) # fileObject.close() # Example: Fix lines bunching up on 1 line. # fileObject = open('alice_output.txt', 'w') # fileObject.write(lines[0] + '\n') # fileObject.write(lines[1]) # fileObject.close() # Example: Write all lines to the file # print('Number of lines in my list:', len(lines)) # fileObject = open('alice_output.txt', 'w') # for line in lines: # fileObject.write(line + '\n') # fileObject.close() '''Time permitting extras''' '''Check if string contains substring''' # Determine whether a string (the subtring) appears / doesn't appear inside another one # Text: 'two wrongs don\'t make a right' # Text: 'right' a = 'two wrongs don\'t make a right' b = 'right' print('Is b in a?', b in a) # boolean print('Is b not in a?', b not in a) # boolean print('Is hi! not in a?', 'hi!' not in a) # boolean '''Other string methods''' # Strings are technically objects and have methods. There are many: # https://docs.python.org/3/library/stdtypes.html#string-methods) # Here are important ones that you should know (minimally): # upper, lower, title, split(char), join, find(word), replace, count # isalpha, isdigit, isupper, isalnum # Example: Let's see some string methods in action. # print(aliceBigString.upper()) # print(aliceBigString.lower()) # print(aliceBigString.title()) # Replace: Example, replace word 'Alice' with '(*girl*)'. Print it out. # aliceReplaced = aliceBigString.replace('Alice', '(*girl*)') # print(aliceReplaced) # Count: Find total number of Is in chapter # print('Number of times the word is appears in Chapter 1:', aliceBigString.count('is')) print(aliceBigString[:20]) print(aliceBigString.find('Adventures'))