Simple sentiment analysis using regular expression

From LemonWiki共筆
Jump to navigation Jump to search

使用 Regular expression 簡易地進行文字的「情感分析」(sentiment analysis)。

輸入文字範例1

我喜歡 pokemon。
我不喜歡 pokemon。
我樂愛 pokemon。
我不樂愛 pokemon。

三種類型情緒

  1. 正面情緒 (positive sentiment)
    • 方式: 搜尋包含「喜歡」、「樂愛」但是前面不緊接「不」字
    • 搜尋: [^不](喜歡|樂愛)
  2. 負面情緒 (negative sentiment)
    • 方式: 搜尋包含「不喜歡」、「不樂愛」
    • 搜尋: [不](喜歡|樂愛)
  3. 中性情緒 (neural sentiment)
    • 方式: 搜尋不包含「喜歡」、「樂愛」
    • 搜尋: ^((?!(喜歡|樂愛)).)*$

但是這樣的搜尋方式,沒有處理到雙重否定 (double negative,負負得正) 比較複雜文法的句子。

輸入文字範例2

我喜歡 pokemon。
我不喜歡 pokemon。
說我不喜歡 pokemon 是錯誤的。
我樂愛 pokemon。
我不樂愛 pokemon。
說我不樂愛 pokemon 是錯誤的。

三種類型情緒

  1. 正面情緒 (positive sentiment)
    • 方式: 搜尋 (1) 包含「喜歡」、「樂愛」但是前面不緊接「不」字 (2) 包含「不喜歡」、「不樂愛」,句子中同時包含否定字串,如例子的「錯誤」。
    • 搜尋:
      • 條件 (1) 搜尋: [^不](喜歡|樂愛)
      • 條件 (2) 搜尋: 找到雙重否定 (?=.*[不](喜歡|樂愛))(?=.*錯誤).*
      • 整合條件 (1) 和條件 (2) 的搜尋: [^不](喜歡|樂愛)|(?=.*[不](喜歡|樂愛))(?=.*錯誤).*
  2. 負面情緒 (negative sentiment)
    • 方式: 搜尋包含「不喜歡」、「不樂愛」,同時句子中同時不包含否定字串,如例子的「錯誤」。
    • 搜尋: ^(?!.*錯誤).([不](喜歡|樂愛)).*$
  3. 中性情緒 (neural sentiment)
    • 方式: 搜尋不包含「喜歡」、「樂愛」
    • 搜尋: ^((?!(喜歡|樂愛)).)*$

延伸閱讀