我是一名學生,從事一個專案,使用 IBM Watson 的 NLU 決議各種新聞文章并回傳情緒分數。我有一個表格中的文章,我設定了一個回圈來遍歷第一列中的每個單元格,對其進行分析,對其進行標準化,并將新資料附加到表格中。
masterdf = pd.DataFrame()
for index, row in df.iterrows():
text2 = row['CONTENT']
response = natural_language_understanding.analyze(
text = text2,
features=Features(sentiment=SentimentOptions(targets=["Irish",]))).get_result()
json_tbl = pd.json_normalize(response['sentiment'],
record_path='targets',
meta=[['document','score'], ['document','label']])
json_tbl = json_tbl.set_index([pd.Index([index])])
print(json_tbl.head())
masterdf = masterdf.append(json_tbl)
masterdf = pd.concat([df, masterdf], axis=1)
masterdf.head()
我遇到的問題是,有時我所針對的物體不在我正在分析的文章中,因此 IBM 會拋出錯誤。這完全破壞了我的代碼。我想要做的是,每當 IBM 回傳錯誤時,我的代碼只是用“N/A”填充該行,然后進入它下面的下一個單元格。我真的是一個初學者,所以任何幫助都會非常感激。
uj5u.com熱心網友回復:
我建議創建一個單獨的函式來封裝所有情緒分析邏輯。最后,你會這樣稱呼它:
df['SENTIMENT_SCORE'] = df['CONTENT'].apply(safe_complex_function)
safe_complex_funtion將是您全新的安全功能。給它起你想要的名字。它可能是這樣的:
def sentiment_scores(content):
try:
response = natural_language_understanding.analyze(
text=content,
features=Features(
sentiment=SentimentOptions(targets=["Irish",])
)
).get_result()
json_tbl = pd.json_normalize(
response['sentiment'],
record_path='targets',
meta=[['document','score'], ['document','label']]
)
return json_tbl.set_index([pd.Index([index])])
except <The specific Exception you want to deal>: # please don't put Exception. It is too general
return None
這是一個示例代碼:
創建測驗資料框
import pandas as pd
data = [
(1, 'I am happy'),
(2, 'I am sad'),
(3, 'I am neutral'),
(4, 'Exception generator')
]
df = pd.DataFrame(data,columns=['USER_ID','CONTENT'])
| 用戶身份 | 內容 | |
|---|---|---|
| 0 | 1 | 我很開心 |
| 1 | 2 | 我很傷心 |
| 2 | 3 | 我是中立的 |
| 3 | 4 | 例外生成器 |
創建嘲諷情緒分析功能
此功能僅用于模擬。
def fake_sentiment_analysis(content):
sentiment_scores = {
'sad': -1,
'happy': 1,
'neutral': 0
}
for sentiment, score in sentiment_scores.items():
if sentiment in content:
return score
## rasises KeyError error only for demonstration purposes
return sentiment_scores['BROKEN']
def complex_function(element):
sentiment_score = fake_sentiment_analysis(element)
return sentiment_score
在 DataFrame 上應用該非安全函式
你會KeyError呼叫那個函式
df['CONTENT'].apply(complex_function)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-22-d418b58879b8> in <module>()
----> 1 df['CONTENT'].apply(complex_function)
2 frames
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-12-538de52b436a> in fake_sentiment_analysis(content)
9 return score
10 ## rasises KeyError error only for demonstration purposes
---> 11 return sentiment_scores['BROKEN']
KeyError: 'BROKEN'
添加例外處理程式
您可以更安全地添加例外處理
def safe_complex_function(element):
try:
sentiment_score = fake_sentiment_analysis(element)
except KeyError:
sentiment_score = None
return sentiment_score
| 用戶身份 | 內容 | SENTIMENT_SCORE | |
|---|---|---|---|
| 0 | 1 | 我很開心 | 1 |
| 1 | 2 | 我很傷心 | -1 |
| 2 | 3 | 我是中立的 | 0 |
| 3 | 4 | 例外生成器 | 南 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369042.html
