使用python代码输出创建CSV文件 [英] Creating CSV file with output of python code

查看:391
本文介绍了使用python代码输出创建CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找编写python代码,该代码将从目录中的多个.txt文件中提取文本,并针对音频分析器"运行文本以进行音频分析.因此,如果我有两个文件ABC.txt和XYZ.txt.我希望对两个文件都进行色调分析,并创建两个输出文件ABC.csv和XYZ.csv,其中包含色调分析的输出,这是我到目前为止的内容:

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 have two files ABC.txt and XYZ.txt. I am looking to do the tone analysis on both the file and create two output files ABC.csv and XYZ.csv containing output of the tone analysis here is what I have so far:

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
ipath = 'C:/TEMP/' # input folder
opath = 'C:/TEMP/matrix/' # output folder
reader = codecs.getreader("utf-8")
tone_analyzer = ToneAnalyzerV3Beta(
    url='https://gateway.watsonplatform.net/tone-analyzer/api',
    username='1f2fd51b-d0fb-45d8-aba2-08e22777b77d',
    password='XYXPASS',
    version='2016-02-11')
path = 'C:/TEMP/*.txt'   
files = glob.glob(path)
# iterate over the list getting each file 
for fle in files:
   # open the file and then call .read() to get the text 
   with open(fle) as f:
      text = f.read()
output = f.replace('txt', 'csv')
output = open(opath + output, mode = 'w')
data=tone_analyzer.tone(text='text')
for cat in data['document_tone']['tone_categories']:
    for tone in cat['tones']:
        print(tone['tone_name'],tone['score'])
        #create file

我能够打印色调分析输出,但是不确定如何将它们分别保存在两个csv文件中.我非常感谢您在这里的任何见解.

I am able to print the tone analysis output but not sure how to save them separately in two csv files. I would really appreciate any insights here.

谢谢

推荐答案

只需将循环输出保存到列表,然后使用csv模块的writerow()将列表写入文件.下面将tone['tone_name']tone['tone_score']数据保存到csv文件中,其中output作为文件名的唯一标识符(扩展名.txt已删除).

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 
    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']:
        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', '')     
    with open(opath + output + '_tonename.csv', mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1) 
        for i in tonename:
             writer.writerow([i])

    with open(opath + output + '_tonescore.csv', mode = 'w') as csvfile2:
        writer = csv.writer(csvfile2) 
        for i in tonescore:
             writer.writerow([i])

如果您需要一个包含两列的csv文件,甚至不需要列表:

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 
    with open(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', '')   
    with open(opath + output + '.csv', mode = 'w') as csvfile:
        writer = csv.writer(csvfile) 
        writer.writerow(['tone_name','score'])                         # HEADERS
        for 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

这篇关于使用python代码输出创建CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆