Difference between revisions of "CSC111 Homework 9 Solution Programs 2014"
(Created page with "--~~~~ ---- > done == hw9a.py == <br /><source lang="python"> def Input( *args ): if len( args )==0: ans = input() print( ans ) return ans ans = input(...") |
|||
Line 1: | Line 1: | ||
--[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:52, 15 April 2014 (EDT) | --[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:52, 15 April 2014 (EDT) | ||
---- | ---- | ||
− | + | ||
+ | |||
== hw9a.py == | == hw9a.py == | ||
<br /><source lang="python"> | <br /><source lang="python"> | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
# hw9a.py | # hw9a.py | ||
# Yumeng Wang(cf) | # Yumeng Wang(cf) |
Revision as of 09:53, 15 April 2014
--D. Thiebaut (talk) 10:52, 15 April 2014 (EDT)
hw9a.py
# hw9a.py
# Yumeng Wang(cf)
#
# A program that can reformat text files and rewrap the text
# in it to a specified width.
#
# 1) ask the user for the name of a file.
# 2) ask the user for the desired width of a line.
# 3) read the content in the file and output
# it as a long string.
# 4) Now we rewrap the texts in the file:
# 4.1) we first split the texts into a list of words
# and create an empty CNNList. Then we use a for
# loop to add each word into the CNNList.
# 4.2) We have another function called "formating"
# which will turn the CNNList into a string and
# and return True if the string is in right format.
# Otherwise, return False.
# 4.3) The next function works when the "formating" returns True.
# It will add the correct string to a new empty list named
# writeBakeText. It then delete all the items in CNNList
# except the last one which is not included in the string with
# desired format.
# 4.4) To be noticed, after the for loop terminates, the last string
# has not been added into our list-"writeBAckText". Thus, we need
# to turn the last CNNList into a tring and add it into writeBackText.
# Return writeBackText.
# 5) Finally, we can write the rewraped texts back to the file. We use "\n"
# to join the writeBackText intoa string. Then write the string back to
# the file.
#
# An example of the format of Input( marked by star ) :
# Please enter the file name: *CNN.txt*
# Please enter the wrapping width: *30*
#
# An example of the output: (the text which would be written
# back to the file.)
# Washington (CNN) -- If you're
# rich and want to give money to
# a lot of political campaigns,
# the Supreme Court ruled
# Wednesday that you can. The
# 5-4 ruling eliminated limits
# on how much money people can
# donate in total in one
# election season. However, the
# decision left intact the
# current $5,200 limit on how
# much an individual can give to
# any single candidate during a
# two-year election cycle. Until
# now, an individual donor could
# give up to $123,200 per cycle.
# ----------------------------------------------------------------------------
# readTextFile( fileName ): It receives the name of the file and open the file
# Then, add all the lines in the file to an empty string. Replace the "\n" in
# the string with " " so that the original format of the texts in the file
# does not matter. Finally, it outputs a string with all the texts of the file.
# ----------------------------------------------------------------------------
def readTextFile( fileName ):
file = open( fileName, "r" )
text = ""
for line in file:
text = text + line
text = text.replace( "\n"," " )
file.close()
return text
# ----------------------------------------------------------------------------
# formating( list, width ): it receives a list and a width. It generates a
# string by joing the items in the list together with a " ". If the length of
# the string ( the characters ) is more than the width, it returns True.
# Otherwise, it returns False.
# ----------------------------------------------------------------------------
def formating( list, width ):
line = " ".join( list )
if len( line ) > width :
return True
else:
return False
# ----------------------------------------------------------------------------
# createNewText( list, newText ): This function receives two lists. It turns
# the first list without the last item into a line(string) and adds it to the
# second list. It then makes a copy of the first list with only the last item
# and returns the list.
# ----------------------------------------------------------------------------
def createNewText( list, newText ):
line = " ".join( list[ : -1] )
newText.append( line )
# reset the list to a list contains only the last item
list = list[-1: ]
return list
# ----------------------------------------------------------------------------
# rewrapText( text, width, newText ): This function receives a string contains
# the texts in the file, the width and a list. It first splits the string
# into a list of words and uses a for loop to add each of the words to an empty
# list. Then, use formating() function. If it returns True, use createNewText()
# function to create a new list and continue the adding in the for loop. When
# the loop terminates, turn the last list into a string and add it to the final
# list that we need and returns that list.
# ----------------------------------------------------------------------------
def rewrapText( text, width, newText ):
words = text.split( " " )
CNNList = []
for i in range (len(words)):
CNNList.append( words[i] )
if formating( CNNList, width ) == True:
CNNList = createNewText( CNNList, newText )
lastLine = " ".join( CNNList )
newText.append( lastLine )
return newText
# ----------------------------------------------------------------------------
# writeTextFile( fileName, text ): This function receives the name of the file
# and a string contains the texts which need to be written in the new file. It
# then uses a for loop to write the text into the file and close the file.
# ----------------------------------------------------------------------------
def writeTextFile( fileName, text ):
file = open( fileName, 'w' )
for line in text:
file.write( line )
file.close()
# =============================================================================
# editFormat():
# -----------------------------------------------------------------------------
# The main function firstly creates an empty list to hold the texts we
# need to write back to the file. Then it asks the user for the name of the file
# and the desired width of the characters per line. Then, it uses readTextFile()
# function to get the list of words in the file. After that, it uses rewrapText()
# to rewrap the texts to the correct format and adds them to the empty list.
# It then joins the list with the seperator "\n" and passes the string to
# wrtiteTextFile() which writes it into the file.
# =============================================================================
def editFormat():
writeBackText = []
fileName = Input("Please enter the file name: ")
width = int(Input("Please enter the wrapping width: "))
print("%s has been rewrapped at a width of %d characters." %( fileName, width))
text = readTextFile( fileName )
rewrapText( text, width, writeBackText )
writeBackText = "\n".join( writeBackText )
# print( writeBackText )
writeTextFile( fileName, writeBackText )
# ===========================================================================
# ---------------------------------------------------------------------------
# main program
# ---------------------------------------------------------------------------
# ===========================================================================
editFormat()
hw9b.py
def Input( *args ):
if len( args )==0:
ans = input()
print( ans )
return ans
ans = input( ' '.join( args ) )
print( ans )
return ans
# hw9b.py
# Yumeng Wang(cf)
#
# This program asks the user for the name of a CSV file containing the data,
# opens it, filters it,goes through all the lines and keeps track of the earthquake(s)
# with the largest magnitude. If several earthquakes have the same largest
# magnitude, it will keep track of all of them.and output the location of the
# strongest earthquake recorded.
#
# 1) ask the user for the name of a file. Open the file and get a list of all lines
# in the file.
#
# An example of the format of Input( marked by star ) :
# Which file do you want to look at: *query.csv*
#
# An example of the output:
# Highest magnitude recorded: 100.0
# Country where 100.0 quakes were recorded: Chile, Indonesia,Owen Fracture Zone
# region, Mexico
#
# 2) makes a copy of the list without the first line in it and makes a new variable
# named magMax. Use the copyed list to find the maximum magnitude in the list
# and stores it int he variable magMax.
# 3) go through all the lines in the list, collect all the countries with the
# maximum magnitude and store those countries in a list named country.
# 4) turn the list of country to a string and make two print statements. The first
# one outputs the maximum magnitude and the second one outputs the location of the
# strongest earthquake recorded.
# ----------------------------------------------------------------------------
# readTextFile( fileName ): It receives the name of the file and open the file
# Then, add all the lines in the file to an empty list. Finally, it returns the
# list which contents all the lines in the file.
# ----------------------------------------------------------------------------
def readTextFile( fileName ):
file = open( fileName, "r" )
text = []
for line in file:
text. append( line )
file.close()
return text
# ----------------------------------------------------------------------------
# levelMax( list, magMax ): this function receives the list of texts in the file
# and a variable named magMax. Then, for all strings in the list, it splits the
# string at commas. It then makes the fifth item in each list as variable level
# and compares level with magMax. If level is bigger than magMax, let magMax
# euqal to level and finally returns magMax - the maximum magnitude.
# ----------------------------------------------------------------------------
def levelMax( list, magMax ):
for line in list:
line = line.split(",")
level = float( line[4] )
if level >= magMax:
magMax = level
return magMax
# ----------------------------------------------------------------------------
# countryMax( list, magMax, country ): This function receives the list of texts
# in the file, the maximum magnitude and an empty country(list). For all strings
# in the list, it replaces ' " ' with '' and splits it at commas into lists. For
# lists in which the fifth item in the list equals to magMax, we add the last
# second item - name of the country into our country list if it is not in the list.
# Finally, returns the list of country.
# ----------------------------------------------------------------------------
def countryMax( list, magMax, country ):
for line in list:
line = line.replace( '"', "")
line = line.split(",")
if float( line [4]) == magMax:
if line[-2] not in country:
country.append( line[-2] )
return country
# =============================================================================
# maxMagCountry():
# -----------------------------------------------------------------------------
# The main function firstly asks the user to input the name of the file. It then
# opens the file and gets a list. Then, it creates a variable magMax which equals
# to 0 and an empty list named "country". Then, it makes a copy of the list except
# the first item in it. Then, use levelMax() function to find the maximum magnitude
# in the file and use countryMax() function to add all the countries with the
# maximun magnitude to the country list. Then, use a space to join the country list
# to a string and print the maximum magnitude and all the countries.
# =============================================================================
def maxMagCountry():
file = Input( "Which file do you want to look at: " )
list = readTextFile( file )
magMax = 0
country = []
# make a copy of the list except the first item in it.
list = list[1: ]
magMax = levelMax( list, magMax )
country = countryMax( list, magMax, country )
# Turn the list into a string.
country = ",".join( country )
print("Highest magnitude recorded:", magMax)
print("Country where %.1f quakes were recorded:" % ( magMax ), country )
# ===========================================================================
# ---------------------------------------------------------------------------
# main program
# ---------------------------------------------------------------------------
# ===========================================================================
maxMagCountry()
hw9c.py
def Input( *args ):
if len( args )==0:
ans = input()
print( ans )
return ans
ans = input( ' '.join( args ) )
print( ans )
return ans
# hw9c.py
# Yumeng Wang(cf)
#
# A program that can reformat text files and rewrap the text
# in it to a specified width. And it will rewrap the text and
# store it back in the file formatted as two columns of text.
# Each column is at most the width specified by the user.
#
# 1) ask the user for the name of a file.
# 2) ask the user for the desired width of a line.
# 3) read the content in the file and output
# it as a long string.
# 4) Now we rewrap the texts in the file:
# 4.1) we first split the texts into a list of words
# and create an empty CNNList. Then we use a for
# loop to add each word into the CNNList.
# 4.2) We have another function called "formating"
# which will turn the CNNList into a string and
# and return True if the string is in right format.
# Otherwise, return False.
# 4.3) The next function works when the "formating" returns True.
# It will add the correct string to a new empty list named
# writeBakeText. It then delete all the items in CNNList
# except the last one which is not included in the string with
# desired format.
# 4.4) To be noticed, after the for loop terminates, the last string
# has not been added into our list-"writeBAckText". Thus, we need
# to turn the last CNNList into a tring and add it into writeBackText.
# Return writeBackText.
# 5) Finally, we can write the rewraped texts back to the file. We use "\n"
# to join the writeBackText intoa string. Then write the string back to
# the file.
#
# An example of the format of Input( marked by star ) :
# Please enter the file name: *CNN.txt*
# Please enter the wrapping width: *30*
#
# An example of the output: (the text which would be written
# back to the file.)
# Washington (CNN) -- If you're election season. However, the
# rich and want to give money to decision left intact the
# a lot of political campaigns, current $5,200 limit on how
# the Supreme Court ruled much an individual can give to
# Wednesday that you can. The any single candidate during a
# 5-4 ruling eliminated limits two-year election cycle. Until
# on how much money people can now, an individual donor could
# donate in total in one give up to $123,200 per cycle.
# ----------------------------------------------------------------------------
# readTextFile( fileName ): It receives the name of the file and open the file
# Then, add all the lines in the file to an empty string. Replace the "\n" in
# the string with " " so that the original format of the texts in the file
# does not matter. Finally, it outputs a string with all the texts of the file.
# ----------------------------------------------------------------------------
def readTextFile( fileName ):
file = open( fileName, "r" )
text = ""
for line in file:
text = text + line
text = text.replace( "\n"," " )
file.close()
return text
# ----------------------------------------------------------------------------
# formating( list, width ): it receives a list and a width. It generates a
# string by joing the items in the list together with a " ". If the length of
# the string ( the characters ) is more than the width, it returns True.
# Otherwise, it returns False.
# ----------------------------------------------------------------------------
def formating( list, width ):
line = " ".join( list )
if len( line ) > width :
return True
else:
return False
# ----------------------------------------------------------------------------
# createNewText( list, newText ): This function receives two lists. It turns
# the first list without the last item into a line(string) and adds it to the
# second list. It then makes a copy of the first list with only the last item
# and returns the list.
# ----------------------------------------------------------------------------
def createNewText( list, newText ):
line = " ".join( list[ : -1] )
newText.append( line )
# reset the list to a list contains only the last item
list = list[-1: ]
return list
# ----------------------------------------------------------------------------
# rewrapText( text, width, newText ): This function receives a string contains
# the texts in the file, the width and a list. It first splits the string
# into a list of words and uses a for loop to add each of the words to an empty
# list. Then, use formating() function. If it returns True, use createNewText()
# function to create a new list and continue the adding in the for loop. When
# the loop terminates, turn the last list into a string and add it to the final
# list that we need and returns that list.
# ----------------------------------------------------------------------------
def rewrapText( text, width, newText ):
words = text.split( " " )
CNNList = []
for i in range (len(words)):
CNNList.append( words[i] )
if formating( CNNList, width ) == True:
CNNList = createNewText( CNNList, newText )
lastLine = " ".join( CNNList )
newText.append( lastLine )
return newText
# ----------------------------------------------------------------------------
# twoColumnList( text, n, width ): This function receives list of texts in the
# file , the length of the file and the width of the first column. It outputs
# the list that each item contains two fileds.
# ----------------------------------------------------------------------------
def twoColumnList( text, n, width ):
content = []
if ((n//2)*2) == n:
half = int(n//2)
for i in range( half ):
text[i] = text[i] + " "* (width-len(text[i]))
content.append( [text[i],text[i + half]])
if ((n//2)*2) != n:
half = int((n-1)//2)
for i in range( half ):
text[i] = text[i] + " "* (width-len(text[i]))
content.append( [text[i],text[i + half + 1]])
content.append( [text[half],""] )
return content
# ----------------------------------------------------------------------------
# twoColumnText( text ): This function receives the list which each item contains
# two fileds and then turns it into a string.
# ----------------------------------------------------------------------------
def twoColumnText( text ):
list = []
for item in text:
line = " ".join(item)
list.append( line )
string = "\n".join( list )
return string
# ----------------------------------------------------------------------------
# writeTextFile( fileName, text ): This function receives the name of the file
# and a string contains the texts which need to be written in the new file. It
# then uses a for loop to write the text into the file and close the file.
# ----------------------------------------------------------------------------
def writeTextFile( fileName, text ):
file = open( fileName, 'w' )
for line in text:
file.write( line )
file.close()
# =============================================================================
# editFormat():
# -----------------------------------------------------------------------------
# The main function firstly creates an empty list to hold the texts we
# need to write back to the file. Then it asks the user for the name of the file
# and the desired width of the characters per line. Then, it uses readTextFile()
# function to get the list of words in the file. After that, it uses rewrapText()
# to rewrap the texts to the correct format and adds them to the empty list.
# It then joins the list with the seperator "\n" and passes the string to
# wrtiteTextFile() which writes it into the file.
# =============================================================================
def editFormat():
n = 0
writeBackText = []
fileName = Input("Please enter the file name: ")
width = int(Input("Please enter the wrapping width: "))
print("%s has been rewrapped at a width of %d characters." %( fileName, width))
text = readTextFile( fileName )
writeBackText = rewrapText( text, width, writeBackText )
length = int(len( writeBackText ))
content = twoColumnList( writeBackText, length, width )
columnContext = twoColumnText( content )
writeTextFile( fileName, columnContext )
# ===========================================================================
# ---------------------------------------------------------------------------
# main program
# ---------------------------------------------------------------------------
# ===========================================================================
editFormat()