我是python的新手,我正在使用以下代码来提取输出作为情感分析:
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='ABCID',
password='ABCPASS',
version='2016-02-11')
path = 'C:/TEMP/*.txt'
file = glob.glob(path)
text = file.read()
data=tone_analyzer.tone(text='text')
for cat in data['document_tone']['tone_categories']:
print('Category:', cat['category_name'])
for tone in cat['tones']:
print('-', tone['tone_name'],tone['score'])
#create file在上面的代码中,我所要做的就是读取文件并对存储在C:/TEMP文件夹中的所有文本文件进行情感分析,但我不断得到错误:'list‘对象没有' read’属性。
不知道我在哪里出错了,我真的很感激在这个问题上的任何帮助。另外,有没有一种方法可以将输出写入CSV文件,这样如果我正在读取该文件
ABC.txt和我用输出值创建了一个名为ABC.csv的输出CSV文件。
谢谢
发布于 2016-05-31 06:06:58
glob返回一个文件列表,您需要迭代该列表,打开每个文件,然后对文件对象调用.read
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()不确定你到底想要写什么,但是csv lib会写的:
from csv import writer
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, open("{}.csv".format(fle.rsplit(".", 1)[1]),"w") as out:
text = f.read()
wr = writer(out)
data = tone_analyzer.tone(text='text')
wr.writerow(["some", "column" ,"names"]) # write the col names然后调用writerow,为每一行传递您想要写入的内容的列表。
https://stackoverflow.com/questions/37534141
复制相似问题