By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,045 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

Splitting Strings in Array and Displaying

P: 2
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,George 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,George Orwell
To Kill A Mockingbird,1960,324,Harper Lee
Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen
***


Expand|Select|Wrap|Line Numbers
  1. def main():
  2.      print("Welcome!")
  3.      arrayBooks = populateBooks()
  4.      displayBookMenu()
  5.  
  6. def displayBookMenu:
  7.      print("\n1: Display All Books")
  8.      print("2: Display Shortest Book")
  9.      print("3: Display Longest Book")
  10.      print("3: Display Oldest Book")
  11.      print("4: Display Newest Book")
  12.      print("0: End")
  13.      choice = int(input("Choice: "))
  14.  
  15.      if choice == 1:
  16.           displayAll()
  17.      elif choice == 2:
  18.           displayShortest()
  19.      elif choice == 3: 
  20.           displayLongest()
  21.      elif choice == 4: 
  22.           displayOldest()
  23.      elif choice == 5:
  24.           displayNewest()
  25.      elif choice == 0:
  26.           exit()
  27.      else:
  28.           print("Invalid Input")
  29.  
  30. def populateBooks():
  31.      fp = open("bookfile.txt", "r")
  32.      return fp.readlines()
  33.  
  34. def displayAll():
  35.  
  36. def displayShortest():
  37.  
  38. def displayLongest():
  39.  
  40. def displayOldest():
  41.  
  42. def displayNewest():
  43.  
  44.  
  45. main()
Oct 5 '14 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 614
You can simply use the return from readlines() and split the record when required.
Expand|Select|Wrap|Line Numbers
  1. test_text="""Animal Farm,1945,152,George Orwell
  2. To Kill A Mockingbird,1960,324,Harper Lee
  3. Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen
  4. """
  5. with open("./bookfile.txt", "w") as fp_out:
  6.     fp_out.write(test_text)
  7.  
  8. book_data=open("./bookfile.txt", "r").readlines()
  9. book_data_1=book_data[1].split(",")
  10. book_data_2=book_data[2].split(",")
  11. print book_data_1[2], book_data_2[2]
  12. print book_data_1[2] == book_data_2[2] 
To place into an array you would append the split record
Expand|Select|Wrap|Line Numbers
  1. book_data=open("./bookfile.txt", "r").readlines()
  2.  
  3. ## to array
  4. test_array=[]
  5. for rec in book_data:
  6.     test_array.append(rec.strip().split(","))
  7. print "\n", test_array
  8. print test_array[1][2], test_array[2][2]
  9. print test_array[1][2]==test_array[2][2] 
Oct 5 '14 #2

P: 2
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:

Expand|Select|Wrap|Line Numbers
  1. def displayBookMenu():
  2.     print("\n1: Display All Books")
  3.     print("2: Display Shortest")
  4.     print("3: Display Longest")
  5.     print("4: Display Oldest")
  6.     print("5: Display Newest")
  7.     print("0: Quit")
  8.     choice = int(input("Choice: "))
  9.  
  10.     if choice==1:
  11.         displayAll(populateBooks())
  12.     elif choice==2:
  13.         displayShortest(arrayBooks)
  14.     elif choice==3:
  15.         pass
  16.     elif choice==4:
  17.         pass
  18.     elif choice==5:
  19.         pass
  20.     elif choice==6:
  21.         pass
  22.     elif choice==0:
  23.         exit()
  24.     else:
  25.         print("Invalid input, please try again.")
  26.  
  27.  
  28.  
  29. def populateBooks():
  30.     lines = [line.strip().split(',') for line in open("bookfile.txt")]
  31.     return lines
  32.  
  33.  
  34.  
  35. def displayAll(arrayBooks):
  36.     print("\nAll Books: \n")
  37.     for books in arrayBooks:
  38.         for each_entry in books:
  39.             print (each_entry),
  40.             print
  41.  
  42.  
  43. def displayShortest():
  44.     list1=[arrayBooks[0][2],arrayBooks[1][2],arrayBooks[2][2]]
  45.     print("Shortest Book: ", min(list1))
  46.  
  47.  
  48. def main():
  49.         print("Welcome!")
  50.         displayBookMenu()
  51.         populateBooks()
  52.         arrayBooks = populateBooks()
  53. #end main
  54.  
  55. 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
Oct 5 '14 #3

Expert 100+
P: 614
The only function in the program that is aware of the return, "lines", is here
Expand|Select|Wrap|Line Numbers
  1. if choice==1:
  2.          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.
Expand|Select|Wrap|Line Numbers
  1.    elif choice==2:
  2.          displayShortest(arrayBooks)
a work-around is
Expand|Select|Wrap|Line Numbers
  1.  def displayBookMenu(arrayBooks):
  2.     print("\n1: Display All Books")
  3.     print("2: Display Shortest Book")
  4.     print("3: Display Longest Book")
  5.     print("3: Display Oldest Book")
  6.     print("4: Display Newest Book")
  7.     print("0: End")
  8.     choice = int(input("Choice: "))
  9.  
  10.     if choice==1:
  11.          displayAll(arrayBooks)  ## passed to the function
  12.     ...
  13.     etc.
  14.  
  15. print("Welcome!")
  16. arrayBooks = populateBooks()  ## catches the return
  17. 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.
Expand|Select|Wrap|Line Numbers
  1. print min(["99", "250", "1001"]) 
Oct 6 '14 #4

Post your reply

Sign in to post your reply or Sign up for a free account.