Skip to main content
 首页 » 编程设计

python之从目录中读取所有文本文件

2025年05月04日10www_RR

我是 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 文件,其中包含输出值。

谢谢

请您参考如下方法:

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 传递一个列表,其中包含您要为每一行写入的内容。