我是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'对象没有属性'读'
不确定我哪里出错了,我真的很感激任何帮助。此外,有没有办法我可以将输出写入CSV文件,所以如果我正在读取文件
ABC.txt和我创建了一个名为ABC.csv的输出CSV文件,其中包含输出值。
谢谢
答案 0 :(得分:8)
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
传递每行要写的内容列表。