我是一个python noob,在我用VADER做过一些情绪分析之后,我在使用MySQLdb操作来更新表时遇到了麻烦。脚本如下所示:
#!/usr/bin/env python
from nltk.tokenize import sent_tokenize
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import MySQLdb as my
try:
db = my.connect(host="*",
user="*",
passwd="*",
db="*")
cur = db.cursor()
cur.execute("SELECT id,content FROM text where relscore >=100")
for row in cur.fetchall():
tableid = row[0]
textin = row[1].rstrip('\n') + ' '
sentences = sent_tokenize(textin)
analyzer = SentimentIntensityAnalyzer()
sum = 0
count = 0
for sentence in sentences:
vs = analyzer.polarity_scores(sentence)
count += 1
sum += vs['compound']
avg = sum / count
cur.execute("update text set sentiment = %s where id = %s",(avg,tableid))
db.close()
except my.Error as e:
print(e)
当我在没有try / except的情况下运行它时,它会按预期运行而不会出现错误,但是数据库中的值没有更新。我添加了try / except以尝试访问来自mysql的任何错误,但是我收到了语法错误
except my.Error as e:
^
IndentationError: unindent does not match any outer indentation level
我没有得到它,因为它似乎与try的缩进级别相匹配,看起来就像我找到的示例。但就像我说我是一个菜鸟所以我可能会遗漏一些明显的东西。
我已经使用调试器验证了select语句正在运行并且正在计算avg,并且已经验证用户对db和table具有必要的权限。任何人都可以帮忙吗?
答案 0 :(得分:0)
您必须在执行查询后(在关闭光标之前)提交更改:
cur.commit()
db.close()
对于try...except
阻止:except
字之前有额外的空格。
答案 1 :(得分:0)
你有一个空格,除了my.Error为e:
删除它并重新测试
#!/usr/bin/env python
from nltk.tokenize import sent_tokenize
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import MySQLdb as my
try:
db = my.connect(host="*", user="*", passwd="*", db="*")
cur = db.cursor()
cur.execute("SELECT `id`, `content` FROM text WHERE `relscore`>=100")
for row in cur.fetchall():
tableid = row[0]
textin = row[1].rstrip('\n') + ' '
sentences = sent_tokenize(textin)
analyzer = SentimentIntensityAnalyzer()
sum = 0
count = 0
for sentence in sentences:
vs = analyzer.polarity_scores(sentence)
count += 1
sum += vs['compound']
avg = sum / float(count)
cur.execute("UPDATE text SET `sentiment` = %s WHERE `id` = %s", (avg,tableid))
db.commit()
cur.close()
db.close()
except Exception as e:
print(e)