简体   繁体   中英

Appending multiple variables to CSV file

This may sound like a question I already asked, but I have a Python code where I am running the text/html file through a tone analyzer and generating the output to a CSV file. The problem I am facing is that I need to write two variables from the output 'Tone_name' and store them as two columns of the same CSV file. Here is the code I have so far (working perfectly for one variable):

import json
from watson_developer_cloud import ToneAnalyzerV3Beta
import urllib.request
import codecs
import csv
import os
import re
import sys
import collections
import glob
import xlwt
ipath = 'C:/TEMP/' # input folder
opath = 'C:/TEMP/' # output folder
reader = codecs.getreader("utf-8")
tone_analyzer = ToneAnalyzerV3Beta(
    url='https://gateway.watsonplatform.net/tone-analyzer/api',
    username='abcid',
    password='pass',
    version='2016-02-11')
path = 'C:/TEMP/*.txt'   
file = glob.glob(path)
# iterate over the list getting each file 
for fle in file:
    # open the file and then call .read() to get the text 
    with open(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']:1
    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', '')     
    X=output
    with open(X+'_tonename.csv', mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1) 
        for i in tonename:
             writer.writerow([i])

Is there a way I can append score as a column along with 'tone_name'?

rows = []
for tone in cat['tones']:
    rows.append((tone['tone_name'],tone['score']))

...

for row in rows:
    writer.writerow(row)

Or more concisely:

writer.writerows((tone['tone_name'],tone['score']) for tone in cat['tones'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM