reading all the text files from directory

后端 未结 1 751
夕颜
夕颜 2021-01-15 18:29

I am new to python and I am using following code to pull output as sentiment analysis:

import json
from watson_developer_cloud import ToneAnalyzerV3Beta
impo         


        
相关标签:
1条回答
  • 2021-01-15 19:01

    glob returns a list of files, you need to iterate over the list, open each file and then call .read on the file object:

    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()
    

    Not sure what it is exactly you want to write but the csv lib will do it:

    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
    

    Then call writerow passing a list of whatever you want to write for each row.

    0 讨论(0)
提交回复
热议问题