gpt4 book ai didi

python - 使用 csv.reader(open(..)..) 时如何修复 “AttributeError: __enter__”?

转载 作者:行者123 更新时间:2023-12-01 09:30:58 24 4
gpt4 key购买 nike

我的代码出现以下错误:

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

我使用了以下代码:

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)

我已经看到了一些其他类似的问题 ( Python Json with returns AttributeError: __enter__ ),但这些解决方案对我的问题不起作用。

有人发现问题了吗?

最佳答案

您没有使用csv.reader正确。它不支持放置在 with statement 内.

尝试按照 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..

换行open而是在 with 中(因为 open 支持它,并且实际上是推荐的使用方式),然后在其中使用 csv.reader

关于python - 使用 csv.reader(open(..)..) 时如何修复 “AttributeError: __enter__”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com