将多个变量附加到CSV文件

时间:2016-06-01 17:19:12

标签: python csv

这可能听起来像我已经问过的问题,但我有一个Python代码,我通过音调分析器运行text / html文件并生成输出到CSV文件。我面临的问题是我需要从输出中写出两个变量' Tone_name'并将它们存储为同一CSV文件的两列。这是我到目前为止的代码(完美地适用于一个变量):

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])

有没有办法可以将得分作为一列添加到' tone_name'?

1 个答案:

答案 0 :(得分:0)

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

...

for row in rows:
    writer.writerow(row)

或者更简洁:

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