Splitting Strings in Array and Displaying

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ad0033
    New Member
    • Oct 2014
    • 2

    Splitting Strings in Array and Displaying

    So, I'm trying to take information from bookfile.txt and display information from it. So far, I've opened the file. I'm having trouble getting each line as one object of arrayBooks.

    I'd like to have arrayBooks[0]="Animal Farm,1945,152,G eorge Orwell"

    Then, I'm going to use book1 = arrayBooks[0].split(',') to split it to other information, such as:
    book1[0]="Animal Farm"
    book1[1]=1945
    book1[2]=152
    book1[3]="George Orwell"

    So, when I want to find the shortest book, I can compare book1[2] to book2[2] and book3[2] to do so.

    My main problem is getting the information in the array and usable. Anything I've tried doesn't seem to work and gives an error in the displayAll() function.

    I'm using the displayAll() as a control because I feel if I can get the information to display, I will have it to use.

    ***
    bookfile.txt:
    Animal Farm,1945,152,G eorge Orwell
    To Kill A Mockingbird,196 0,324,Harper Lee
    Pride and Prejudice,1813, 279,Jane Austen and Anna Quindlen
    ***


    Code:
    def main():
         print("Welcome!")
         arrayBooks = populateBooks()
         displayBookMenu()
    
    def displayBookMenu:
         print("\n1: Display All Books")
         print("2: Display Shortest Book")
         print("3: Display Longest Book")
         print("3: Display Oldest Book")
         print("4: Display Newest Book")
         print("0: End")
         choice = int(input("Choice: "))
    
         if choice == 1:
              displayAll()
         elif choice == 2:
              displayShortest()
         elif choice == 3: 
              displayLongest()
         elif choice == 4: 
              displayOldest()
         elif choice == 5:
              displayNewest()
         elif choice == 0:
              exit()
         else:
              print("Invalid Input")
    
    def populateBooks():
         fp = open("bookfile.txt", "r")
         return fp.readlines()
    
    def displayAll():
    
    def displayShortest():
    
    def displayLongest():
    
    def displayOldest():
    
    def displayNewest():
    
    
    main()
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    You can simply use the return from readlines() and split the record when required.
    Code:
    test_text="""Animal Farm,1945,152,George Orwell
    To Kill A Mockingbird,1960,324,Harper Lee
    Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen
    """
    with open("./bookfile.txt", "w") as fp_out:
        fp_out.write(test_text)
    
    book_data=open("./bookfile.txt", "r").readlines()
    book_data_1=book_data[1].split(",")
    book_data_2=book_data[2].split(",")
    print book_data_1[2], book_data_2[2]
    print book_data_1[2] == book_data_2[2]
    To place into an array you would append the split record
    Code:
    book_data=open("./bookfile.txt", "r").readlines()
    
    ## to array
    test_array=[]
    for rec in book_data:
        test_array.append(rec.strip().split(","))
    print "\n", test_array
    print test_array[1][2], test_array[2][2]
    print test_array[1][2]==test_array[2][2]

    Comment

    • ad0033
      New Member
      • Oct 2014
      • 2

      #3
      Thank you! I've tried a few things and got the file to open and display all, I'm having a hard time using the individual information from the lines pulled.
      Here's what I have now:

      Code:
      def displayBookMenu():
          print("\n1: Display All Books")
          print("2: Display Shortest")
          print("3: Display Longest")
          print("4: Display Oldest")
          print("5: Display Newest")
          print("0: Quit")
          choice = int(input("Choice: "))
      
          if choice==1:
              displayAll(populateBooks())
          elif choice==2:
              displayShortest(arrayBooks)
          elif choice==3:
              pass
          elif choice==4:
              pass
          elif choice==5:
              pass
          elif choice==6:
              pass
          elif choice==0:
              exit()
          else:
              print("Invalid input, please try again.")
      
      
      
      def populateBooks():
          lines = [line.strip().split(',') for line in open("bookfile.txt")]
          return lines
      
      
      
      def displayAll(arrayBooks):
          print("\nAll Books: \n")
          for books in arrayBooks:
              for each_entry in books:
                  print (each_entry),
                  print
      
      
      def displayShortest():
          list1=[arrayBooks[0][2],arrayBooks[1][2],arrayBooks[2][2]]
          print("Shortest Book: ", min(list1))
      
      
      def main():
              print("Welcome!")
              displayBookMenu()
              populateBooks()
              arrayBooks = populateBooks()
      #end main
      
      main()
      I've got it to display all the Books, but when I try to put the pages in a list to find the min, I get errors about the list/arrayBooks

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        The only function in the program that is aware of the return, "lines", is here
        Code:
        if choice==1:
                 displayAll(populateBooks())
        None of the other functions in the program know about the file read. You should be using a class for this program as you can eliminate those problems easily.

        For option #2, arrayBooks is not known by this function, only the main() function knows about it, see here for info on passing parameters.
        Code:
           elif choice==2:
                 displayShortest(arrayBooks)
        a work-around is
        Code:
         def displayBookMenu(arrayBooks):
            print("\n1: Display All Books")
            print("2: Display Shortest Book")
            print("3: Display Longest Book")
            print("3: Display Oldest Book")
            print("4: Display Newest Book")
            print("0: End")
            choice = int(input("Choice: "))
        
            if choice==1:
                 displayAll(arrayBooks)  ## passed to the function
            ...
            etc.
        
        print("Welcome!")
        arrayBooks = populateBooks()  ## catches the return
        displayBookMenu(arrayBooks)   ## passes the array to the function
        Finally, I would suggest that you include some test book in the file with 99 pages, as it won't print the min that you think it would because you are using strings (evaluates left to right), not integers.
        Code:
        print min(["99", "250", "1001"])

        Comment

        Working...