我是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
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我所要做的就是读取文件并对存储在C:/ TEMP文件夹中的所有文本文件进行情绪分析但是我一直得到并且错误:'list'对象没有属性'read'
不知道我哪里出错了,我真的很感激这个问题的任何帮助.此外,有没有办法我可以将输出写入CSV文件,所以如果我正在读取文件
ABC.txt和我创建一个名为ABC.csv的输出CSV文件,带有输出值.
谢谢
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()
Run Code Online (Sandbox Code Playgroud)
不确定你想写什么,但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
Run Code Online (Sandbox Code Playgroud)
然后调用writerow传递每行要写的任何内容的列表.
| 归档时间: |
|
| 查看次数: |
13240 次 |
| 最近记录: |