How would I write a code to read in this book.txt

title*Programming PHP
author*Lerdorf, Tatroe and MacIntyre
publisher*O'Reilly Media
description*3
This book covers the PHP programming language.
It assumes the reader has some programming experience.
It covers connecting to Oracle and MySQL databases.
title*Core PHP Programming
author*Atkinson
publisher*Pearson Education
description*3
This book starts with an introduction to PHP.
It covers PHP's built-in functions and also
discusses some searching and sorting algorithms

and turn it into a json file like this

{
  "books": [
    {"title":"Programming PHP",
     "author":"Lerdorf, Tatroe and MacIntyre",
     "publisher":"O'Reilly Media",
     "description":
      [
        "This book covers the PHP programming language.",
        "It assumes the reader has some programming experience.",
        "It covers connecting to Oracle and MySQL databases."
      ]
    },
    {"title":"Core PHP Programming",
     "author":"Atkinson",
     "publisher":"Pearson Education",
     "description":
      [
        "This book starts with an introduction to PHP.",
        "It covers PHP's built-in functions and also",
        "discusses some searching and sorting algorithms"
      ]
    }
  ]
}

. I'm thinking this a dictionary, but I don't know much. Please if you help me can you write a simplest code in python, Thank-you for the help.

Recommended Answers

All 9 Replies

For lines in file split the line from star. If part after star is number put that number of values to list value, then continue normaly. Change book if first part is title. Write out with json module.

@tonyjv,

Can you please give me a little example? Thank-you :)

print 'sdfa * dsfa'.split('*')

Show own effort and ask if you get stuck.

@tonyjv,

This is what i have now, I'm stressing on this extra credit for school help please

infile = open("books.txt","r")
lines = infile.readlines()
infile.close()
print '{'
print '  "books":'
print '     "["'
for i in range(0, len(lines)):
    commas = lines[i].split('*')
    if (commas[0] == 'title'):
        print commas
    
        for i in range(0, len(commas)):
            if (commas[i] == 'author'):

                print commas   
    
print '        "}"'
print '        "{"'
print '        "}"'
print '     "]"'
print '}'

I'm pulling my hair trying to figure this out.

Can not use json module? Where is match for line 17? How about ':'s?

tonyjv,

I have this so far, I can't get it to print the lines after the descriptions, please help thank-you :)

infile = open("books.txt","r")
lines = infile.readlines()
infile.close()
print '{'
print '  "books":'
print '     "["'
for i in range(0, len(lines)):
    commas = lines[i].split('*')
    if (commas[0] == 'title'):
        print ' {"title"'':''"',commas[1]
    elif (commas[0] == 'author'):
        print ' "author"'':''"',commas[1]
    elif (commas[0] == 'publisher'):
        print ' "publisher"'':''"',commas[1]
    for i in range(0, len(commas)):
        if (commas[0] == 'description'):
            print '"description"'':',commas[1],"\n" '['
        elif (commas[1] == '3'):# from this line i'm taking a guess, i'm lost... 
            print description

I coded your job, and it is more complicated than it looks, at least avoiding the kind of hard wired words approach you started.

I wrote few helper functions to do the indentation by putting indent*' ' before the lines and adding the ':'s and ','s and one simple quote function which returns parameter string inside double quotes as normal standard is single quotes for the repr function.

Looks that the complication of not putting commas after last elements is bit ugly, so I recommentd you to code the indentation routine, but instead of direct printing to return the file content as string. Then it is possible to ',\n'.join(books), when books contains the list of strings of all books in file. Notice that start indention of books info is 2, not zero, you must set up that before calling the indented info preparing function for each block of book lines. Alternative of recursive function with indentation parameter, check out my list pretty printer:
http://www.daniweb.com/code/snippet281208.html

Some modifications to your code
1. Used a list for keywords instead of if() statements
2. Added an indicator that turns on when "description" is found and prints those records. Add whatever to want to process those records instead of the print statement under "if des".

infile = open("books.txt","r")
lines = infile.readlines()
infile.close()
keywords = ("title", "author", "publisher") 
print '{'
print '  "books":'
print '     "["'
des = False

for ctr in range(0, len(lines)):
    commas = lines[ctr].split('*')

    ## look in a tuple instead of testing each with an if() statement
    if commas[0] in keywords:
        print ' {"%s":"%s"' % (commas[0], commas[1])

        ## some other keyword = set "description" to False
        des = False
    elif commas[0] == "description":
        print "-"*50
        des = True

    ## assuming you want to print the "description" line also
    if des:
        print lines[ctr]

@tonyjv,

Your like the master of python, but your code looks really too advance for me. Thank-you for taking the time to help me...love ya :)

@woooee,

Dam, your my hero, wish I could buy you a beer :)

Thank-you to both of you for helping me :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.