繁体   English   中英

将多个变量附加到CSV文件

[英]Appending multiple variables to CSV file

这可能听起来像我已经问过的问题,但我有一个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'一起添加?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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