我正在尝试运行python代码来输入多个文本文件(例如ABC.txt和XYZ.txt)并使用输出创建多个CSV文件(例如ABC.csv和XYZ.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/matrix/' # output folder
reader = codecs.getreader("utf-8")
tone_analyzer = ToneAnalyzerV3Beta(
url='https://gateway.watsonplatform.net/tone-analyzer/api',
username='ID',
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']:
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])
以上代码将两个文件作为输入' Testdata'和' Testdata-copy'>当我运行此代码时,我收到以下错误:
无效参数:' C:/ TEMP / matrix / C:/ TEMP \ Testdata - Copy_tonename.csv'
我想当代码尝试附加第二个文件时,它会将整个路径作为参数。我不知道如何绕过它。这里的任何输入都将非常感激。
谢谢。