473,387 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Splitting Strings in Array and Displaying

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
3 1661
dwblas
626 Expert 512MB
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
ad0033
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
dwblas
626 Expert 512MB
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

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

Similar topics

5
by: Steven Bethard | last post by:
Here's what I'm doing: >>> lst = >>> splits = >>> for s in lst: .... pair = s.split(':') .... if len(pair) != 2: .... pair.append(None) .... splits.append(pair) ....
7
by: Jeremy Sanders | last post by:
I have a large string containing lines of text separated by '\n'. I'm currently using text.splitlines(True) to break the text into lines, and I'm iterating over the resulting list. This is very...
3
by: Aaron Walker | last post by:
I have a feeling this going to end up being something so stupid, but right now I'm confused as hell. I'm trying to code a function, that given a string and a delimiter char, returns a vector of...
6
by: vladislavf | last post by:
Hi All, I need to pass array of strings from C++/CLI to unmanaged C++ function. (The unmanaged API signatire is : int Combine(int NumOfInputFiles, wchar_t **names) and I want to call it from...
8
by: Jared.Holsopple | last post by:
Hi all, I have a dynamically allocated array of doubles in VC++ .NET. When I view the array in the watch window with "arrayName, 10", it displays the correct value for arrayName, but arrayName...
4
by: r035198x | last post by:
Breaking up a string Instead of using the old StringTokenizer class, a simple trick is to use the String.split method. String string = "This is a string"; String tokens = string.split("...
13
by: pereges | last post by:
I've an array : {100,20, -45 -345, -2 120, 64, 99, 20, 15, 0, 1, 25} I want to split it into two different arrays such that every number <= 50 goes into left array and every number 50 goes...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.