tags:

views:

71

answers:

4

I'm dealing with an application that exports text as as CSV type data. The text is broken up into fields where there was a hard return. I have been trying to use pythons CSV to restore the text.

This is an example of the text:

{"This is an example", "of what I what I have to deal with.  ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}

What is the best way to read this output this text like so:

This is an example
of what I have to deal with.
Please pick up the following:
eggs
milk
Thanks for picking up the groceries for me

I have tried a number of ways that just haven't been quite right.

Here is what I am doing so far:

import csv
import xlrd
book = xlrd.open_workbook("book1.xls")
sh = book.sheet_by_index(0)
cat = 'Mister Peanuts'

for r in range(sh.nrows)[0:]:
    cat_name = sh.cell_value(rowx=r, colx=1)
    cat_behavior = sh.cell_value(rowx=r, colx=5)

    if sh.cell_value(rowx=r, colx=1) == cat :       
        csv_reader = csv.reader( ([ cat_behavior ]), delimiter=',') 
        for row in csv_reader:

                for item in row:
                        item = item.strip()
                        print(item)
            pass    
    pass

So, the actual cell value that is returned for cat_behavior is the following:

['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', '  "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']

I am now trying to take the above and run in through csv.reader to sanitize it and print it to a text file. I am now trying to make the (item) look normal.

A: 

You will need to look into csv.writer to export data to csv, rather than csv.reader.

EDIT: The body and title of question conflict. You're right about using csv.reader.You can use print in a for loop to achieve the result you are after.

Tim McNamara
Thanks, Tim. I am very close now using that method!
SPORKEATER
A: 
import csv
with open('test') as f:
    for row in csv.reader(f):
        for item in row:
            item=item.strip('{} "')
            print(item)

The strip method removes the specified characters from the left or right end of the string item.

unutbu
Thanks so much. This did help me move forward. The problem is that the CSV may actually have squiggly brackets and quotations which could be a problem.
SPORKEATER
+1  A: 

Please explain what you have got to start with.

x = {"This is an example", ......., "Thanks for picking groceries up for me"}

That looks like a set. Then you pass [x] as the first arg of csv.reader!! That doesn't work:

[Python 2.7]
>>> import csv
>>> x = {"foo", "bar", "baz"}
>>> rdr = csv.reader([x]) # comma is the default delimiter
>>> list(rdr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected string or Unicode object, set found
>>>

You say "application that exports text as as CSV type data" -- what does "exports" mean? If it means "writes to a file", please (if you can't follow the examples dotted all over the web) give us a dump of the file to look at. If it means "method/function returns a python object", please do print(repr(python_object)) and update your question with a copy/paste of the print output.

What documentation about the application output do you have?

Update after comments and question edited:

You say that the cell value "returned" was:

['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', ' "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']

This looks like what you printed after passing the ACTUAL data through the CSV mangle, not the raw value extracted by xlrd, which certainly won't be a list; it would be a single unicode object.

In case you didn't read it before: Please explain what you have got to start with.

Do you think it possible to do these:

(1) please do print(repr(cat_behavior)) and update your question with a copy/paste of the print output.

(2) say what documentation you have about the application that creates the Excel file.

John Machin
I am using your xlrd to extract cells from the spreadsheet and then printing those cell values into a text file that someone can actually read. One of the cells that I need to print contains CSV like data. So, I am trying to make that text readable before printing it to the text file.
SPORKEATER
I have edited to show what I am actually doing with an actual piece of text from the cell.
SPORKEATER
A: 
>>> s
'{"This is an example", "of what I what I have to deal with.  ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}'

>>> print s.replace(",","\n").replace("{","").replace("}","").replace('"',"")
This is an example
 of what I what I have to deal with.
 Please pick up th following:
 eggs
 milk
 Thanks for picking groceries up for me

>>> open("output.csv","w").write( s.replace(",","\n").replace("{","").replace("}","").replace('"',"") )
ghostdog74
Thanks. I am a newbie to python, but won't this cause a problem if there are nested quotations or curly brackets? This is an unfortunate possibility.
SPORKEATER
if you have nested stuffs, then don't use this method.
ghostdog74
There shouldn't be too much nesting in CSV files.
Tim McNamara