6

I get the following error with my code:

Traceback (most recent call last):
File "C:\Users\XXX\Sentiment Analysis-vader.py", line 34, in <module>
    f.printer()

File "C:\Users\XXX\Sentiment Analysis-vader.py", line 18, in printer
    with csv.reader(open('analyse_' + str(bloombergcode) + '.csv', 'r'), delimiter= ",",quotechar='|') as q2:

AttributeError: __enter__

Process finished with exit code 1

I used the following code:

import csv
from nltk.sentiment.vader import SentimentIntensityAnalyzer

class VaderSentiment:
    def __init__(self, bloomcode):
        self.bloomcode = bloomcode

    def print_sentiment_scores(self, sentence):
        self.sentence = sentence
        analyser = SentimentIntensityAnalyzer()
        snt = analyser.polarity_scores(self.sentence)
        print("{:-<40} {}".format(self.sentence, str(snt)))

    def printer(self):
        bloombergcode = self.bloomcode
        with csv.reader(open('analyse_' + str(bloombergcode) + '.csv', 'r'), delimiter= ",",quotechar='|') as q2:
            for line in q2:
                for field in line:
                    print_sentiment_scores(field)

for code in ('AAPL', 'NFLX'):
    f = VaderSentiment(code)
    f.printer()
    time.sleep(1)

I already saw some other similar problems (Python Json with returns AttributeError: __enter__) but the solutions do not work on my problem.

Does anyone see the problem?

1 Answer 1

9

You're not using csv.reader correctly. It does not support being placed inside a with statement.

Try to do it the same way as in the usage example:

with open('analyse_' + str(bloombergcode) + '.csv', 'r') as csv_file:
    q2 = csv.reader(csv_file, delimiter=',', quotechar='|')
    for line in q2:
        # ..rest of your code..

Wrap open instead inside the with (because open supports it and is actually the recommended way of using it) then use csv.reader inside it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.