Creating Csv File With Output Of Python Code
I am looking to write a python code that will take the text from multiple .txt files in a directory and run the text against 'Tone analyzer' to do the analysis of the tone. So if I
Solution 1:
Simply save loop output to lists and then use csv
module's writerow()
to write lists to file. Below will save tone['tone_name']
and tone['tone_score']
data to csv files with output
serving as the unique identifier in file name (extension .txt removed).
...
# iterate over the list getting each file for fle in files:
# open the file and then call .read() to get the text withopen(fle) as f:
text = f.read()
# tone analysis
data=tone_analyzer.tone(text='text')
# iterate through tone analysis data
tonename=[]; tonescore=[]
for cat in data['document_tone']['tone_categories']:
for tone in cat['tones']:
tonename.append(tone['tone_name'])
tonescore.append(tone['score'])
print(tone['tone_name'],tone['score'])
# output tone name and score to file
output = fle.replace('.txt', '')
withopen(opath + output + '_tonename.csv', mode = 'w') as csvfile1:
writer = csv.writer(csvfile1)
for i in tonename:
writer.writerow([i])
withopen(opath + output + '_tonescore.csv', mode = 'w') as csvfile2:
writer = csv.writer(csvfile2)
for i in tonescore:
writer.writerow([i])
Should you need one csv file containing both columns, no lists are even needed:
for fle in files:
# open the file and then call .read() to get the text withopen(fle) as f:
text = f.read()
# tone analysis
data=tone_analyzer.tone(text='text')
# output tone name and score to file
output = fle.replace('.txt', '')
withopen(opath + output + '.csv', mode = 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['tone_name','score']) # HEADERSfor cat in data['document_tone']['tone_categories']:
for tone in cat['tones']:
print(tone['tone_name'],tone['score'])
writer.writerow([tone['tone_name'],tone['score']]) # ROWS
Post a Comment for "Creating Csv File With Output Of Python Code"