import aip import time import pandas as pd from tqdm import tqdm content_list = [] positive_prob_list = [] negative_prob_list = [] def sentiment_classify(txt): client_appid = '34468201' client_ak = 'U3tHxNzzm3z89wXRpjSswVv3' client_sk = 'qlbLtgMcUg75Mmfd4ei1puzLXPpNgDfC' my_nlp = aip.nlp.AipNlp(client_appid, client_ak, client_sk) results = my_nlp.sentimentClassify(txt) positive_prob = results['items'][0]['positive_prob'] negative_prob = results['items'][0]['negative_prob'] content_list.append(txt) positive_prob_list.append(positive_prob) negative_prob_list.append(negative_prob) return positive_prob df = pd.read_excel('/Users/26921/Desktop/shuju/20000-30000.xlsx') txt_content = df["content"] positive_times = 0 negative_times = 0 for txt in tqdm(txt_content): if sentiment_classify(txt) > 0.5: positive_times += 1 else: negative_times += 1 df_res = pd.DataFrame({"content": content_list, "positive_prob":positive_prob_list, "negative_prob":negative_prob_list}) df_res.to_excel("/Users/26921/Desktop/shuju/20000-30000(2).xlsx") print("分析完成,正向{}条,负向{}条!".format(positive_times, negative_times))优化这段代码,使其出现'items'错误时,跳过错误继续执行程序
时间: 2024-03-23 19:39:14 浏览: 17
要优化这段代码,可以在 `sentiment_classify()` 函数中使用异常处理语句,避免出现 'items' 错误时程序崩溃。以下是修改后的代码:
```
import aip
import time
import pandas as pd
from tqdm import tqdm
content_list = []
positive_prob_list = []
negative_prob_list = []
def sentiment_classify(txt):
client_appid = '34468201'
client_ak = 'U3tHxNzzm3z89wXRpjSswVv3'
client_sk = 'qlbLtgMcUg75Mmfd4ei1puzLXPpNgDfC'
my_nlp = aip.nlp.AipNlp(client_appid, client_ak, client_sk)
try:
results = my_nlp.sentimentClassify(txt)
positive_prob = results['items'][0]['positive_prob']
negative_prob = results['items'][0]['negative_prob']
content_list.append(txt)
positive_prob_list.append(positive_prob)
negative_prob_list.append(negative_prob)
return positive_prob
except:
print("分析出错:", txt)
return None
df = pd.read_excel('/Users/26921/Desktop/shuju/20000-30000.xlsx')
txt_content = df["content"]
positive_times = 0
negative_times = 0
for txt in tqdm(txt_content):
if sentiment_classify(txt) is not None:
if sentiment_classify(txt) > 0.5:
positive_times += 1
else:
negative_times += 1
df_res = pd.DataFrame({"content": content_list, "positive_prob":positive_prob_list, "negative_prob":negative_prob_list})
df_res.to_excel("/Users/26921/Desktop/shuju/20000-30000(2).xlsx")
print("分析完成,正向{}条,负向{}条!".format(positive_times, negative_times))
```
在修改后的代码中,我们在 `sentiment_classify()` 函数中使用了 try-except 语句。如果出现 'items' 错误,程序会跳过当前循环并打印出错信息,然后继续执行下一次循环。同时,在主函数中调用 `sentiment_classify()` 函数时,我们增加了一个判断,如果返回值为 None,则不执行后续的判断语句,而是直接跳过当前循环。这样就避免了出现错误时程序崩溃的问题。