Skip to content Skip to sidebar Skip to footer

Text Analysis-unable To Write Output Of Python Program In Csv Or Xls File

Hi I am trying to do a sentiment analysis using Naive Bayes classifier in python 2.x. It reads the sentiment using a txt file and then gives output as positive or negative based on

Solution 1:

I've checked the github repo posted by you in comments. I tried to run the project, but I have some errors.

Anyway, I've checked the project structure and the file used to training the naive bayes algorithm, and I think that the following piece of code can be used to write your result data in a Excel file (i.e. .xls)

withopen("test11.txt") as f:
    for line in f:
        classifier= naive_bayes_classifier(positive, negative, total_negative, total_positive, line)
        result='Positive' if classifier==0else'Negative'
        data_to_be_written += ([line, result],)

# Create a workbook andadd a worksheet.
workbook = xlsxwriter.Workbook('test.xls')
worksheet = workbook.add_worksheet()

# Startfrom the first cell. Rowsand columns are zero indexed.
row=0
col =0

# Iterate over the data and write it outrowby row.
for item, cost in data_to_be_written:
   worksheet.write(row, col,     item)
worksheet.write(row, col +1, cost)
row+=1

workbook.close()

Sorthly, for each row of the file with the sentences to be tested, I call the classifier and prepare a structure that will be written in the csv file. Then loop the structure and write the xls file. To do this I have used a python site package called xlsxwriter.

As I told you before, I have some problem to run the project, so this code is not tested as well. It should be works well, bu anyway, if you are in trouble, let me know.

Regards

Solution 2:

> with open("test11.txt") as f:> for line in f:>         classifier = Naive_Bayes_Classifier(positive, negative, total_negative, total_positive, line) if classifier == 0:>       f.write(line + 'Negative') else:>        f.write(line + 'Positive')> > #        result = 'Positive' if classifier == 0 else 'Negative'> #        data_to_be_written += ([line, result],)> 
> # Create a workbook and add a worksheet. workbook = xlsxwriter.Workbook('test.xls') worksheet = workbook.add_worksheet()> 
> # Start from the first cell. Rows and columns are zero indexed. row = 0 col = 0> 
> # Iterate over the data and write it out row by row. for item, cost in f:    worksheet.write(row, col,     item) worksheet.write(row, col +> 1, cost) row += 1> 
> workbook.close()

Post a Comment for "Text Analysis-unable To Write Output Of Python Program In Csv Or Xls File"