2013-03-27 2 views
5

Je dois faire une analyse de sentiment sur certains fichiers CSV contenant des tweets. J'utilise SentiWordNet pour faire l'analyse de sentiment.Comment utiliser SentiWordNet

J'ai obtenu le morceau d'exemple de code java qu'ils ont fourni sur leur site. Je ne suis pas sûr de savoir comment l'utiliser. Le chemin du fichier csv que je veux analyser est C:\Users\MyName\Desktop\tweets.csv. Le chemin du SentiWordNet_3.0.0.txt est C:\Users\MyName\Desktop\SentiWordNet_3.0.0\home\swn\www\admin\dump\SentiWordNet_3.0.0_20130122.txt. Je suis nouveau à Java, l'aide de pls, merci! Le lien vers l'exemple de code Java ci-dessous est this.

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Set; 
import java.util.Vector; 

public class SWN3 { 
    private String pathToSWN = "data"+File.separator+"SentiWordNet_3.0.0.txt"; 
    private HashMap<String, String> _dict; 

    public SWN3(){ 

     _dict = new HashMap<String, String>(); 
     HashMap<String, Vector<Double>> _temp = new HashMap<String, Vector<Double>>(); 
     try{ 
      BufferedReader csv = new BufferedReader(new FileReader(pathToSWN)); 
      String line = "";   
      while((line = csv.readLine()) != null) 
      { 
       String[] data = line.split("\t"); 
       Double score = Double.parseDouble(data[2])-Double.parseDouble(data[3]); 
       String[] words = data[4].split(" "); 
       for(String w:words) 
       { 
        String[] w_n = w.split("#"); 
        w_n[0] += "#"+data[0]; 
        int index = Integer.parseInt(w_n[1])-1; 
        if(_temp.containsKey(w_n[0])) 
        { 
         Vector<Double> v = _temp.get(w_n[0]); 
         if(index>v.size()) 
          for(int i = v.size();i<index; i++) 
           v.add(0.0); 
         v.add(index, score); 
         _temp.put(w_n[0], v); 
        } 
        else 
        { 
         Vector<Double> v = new Vector<Double>(); 
         for(int i = 0;i<index; i++) 
          v.add(0.0); 
         v.add(index, score); 
         _temp.put(w_n[0], v); 
        } 
       } 
      } 
      Set<String> temp = _temp.keySet(); 
      for (Iterator<String> iterator = temp.iterator(); iterator.hasNext();) { 
       String word = (String) iterator.next(); 
       Vector<Double> v = _temp.get(word); 
       double score = 0.0; 
       double sum = 0.0; 
       for(int i = 0; i < v.size(); i++) 
        score += ((double)1/(double)(i+1))*v.get(i); 
       for(int i = 1; i<=v.size(); i++) 
        sum += (double)1/(double)i; 
       score /= sum; 
       String sent = "";    
       if(score>=0.75) 
        sent = "strong_positive"; 
       else 
       if(score > 0.25 && score<=0.5) 
        sent = "positive"; 
       else 
       if(score > 0 && score>=0.25) 
        sent = "weak_positive"; 
       else 
       if(score < 0 && score>=-0.25) 
        sent = "weak_negative"; 
       else 
       if(score < -0.25 && score>=-0.5) 
        sent = "negative"; 
       else 
       if(score<=-0.75) 
        sent = "strong_negative"; 
       _dict.put(word, sent); 
      } 
     } 
     catch(Exception e){e.printStackTrace();}   
    } 

    public String extract(String word, String pos) 
    { 
     return _dict.get(word+"#"+pos); 
    } 
} 

Code alternatif:

public class SWN3 { 
     private String pathToSWN = "C:\\Users\\MyName\\Desktop\\SentiWordNet_3.0.0\\home\\swn\\www\\admin\\dump\\SentiWordNet_3.0.0.txt"; 
    private HashMap<String, String> _dict; 

    public SWN3(){ 

     _dict = new HashMap<String, String>(); 
     HashMap<String, Vector<Double>> _temp = new HashMap<String, Vector<Double>>(); 
     try{ 
      BufferedReader csv = new BufferedReader(new FileReader(pathToSWN)); 
      String line = "";   
      while((line = csv.readLine()) != null) 
      { 
       String[] data = line.split("\t"); 
       Double score = Double.parseDouble(data[2])-Double.parseDouble(data[3]); 
       String[] words = data[4].split(" "); 
       for(String w:words) 
       { 
        String[] w_n = w.split("#"); 
        w_n[0] += "#"+data[0]; 
        int index = Integer.parseInt(w_n[1])-1; 
        if(_temp.containsKey(w_n[0])) 
        { 
         Vector<Double> v = _temp.get(w_n[0]); 
         if(index>v.size()) 
          for(int i = v.size();i<index; i++) 
           v.add(0.0); 
         v.add(index, score); 
         _temp.put(w_n[0], v); 
        } 
        else 
        { 
         Vector<Double> v = new Vector<Double>(); 
         for(int i = 0;i<index; i++) 
          v.add(0.0); 
         v.add(index, score); 
         _temp.put(w_n[0], v); 
        } 
       } 
      } 
      Set<String> temp = _temp.keySet(); 
      for (Iterator<String> iterator = temp.iterator(); iterator.hasNext();) { 
       String word = (String) iterator.next(); 
       Vector<Double> v = _temp.get(word); 
       double score = 0.0; 
       double sum = 0.0; 
       for(int i = 0; i < v.size(); i++) 
        score += ((double)1/(double)(i+1))*v.get(i); 
       for(int i = 1; i<=v.size(); i++) 
        sum += (double)1/(double)i; 
       score /= sum; 
       String sent = "";    
       if(score>=0.75) 
        sent = "strong_positive"; 
       else 
       if(score > 0.25 && score<=0.5) 
        sent = "positive"; 
       else 
       if(score > 0 && score>=0.25) 
        sent = "weak_positive"; 
       else 
       if(score < 0 && score>=-0.25) 
        sent = "weak_negative"; 
       else 
       if(score < -0.25 && score>=-0.5) 
        sent = "negative"; 
       else 
       if(score<=-0.75) 
        sent = "strong_negative"; 
       _dict.put(word, sent); 
      } 
     } 
     catch(Exception e){e.printStackTrace();}   
    } 

    public Double extract(String word) 
    { 
     Double total = new Double(0); 
     if(_dict.get(word+"#n") != null) 
      total = _dict.get(word+"#n") + total; 
     if(_dict.get(word+"#a") != null) 
      total = _dict.get(word+"#a") + total; 
     if(_dict.get(word+"#r") != null) 
      total = _dict.get(word+"#r") + total; 
     if(_dict.get(word+"#v") != null) 
      total = _dict.get(word+"#v") + total; 
     return total; 
    } 

    public String classifytweet(){ 
     String[] words = twit.split("\\s+"); 
     double totalScore = 0, averageScore; 
     for(String word : words) { 
      word = word.replaceAll("([^a-zA-Z\\s])", ""); 
      if (_sw.extract(word) == null) 
       continue; 
      totalScore += _sw.extract(word); 
     } 
     Double AverageScore = totalScore; 

     if(averageScore>=0.75) 
      return "very positive"; 
     else if(averageScore > 0.25 && averageScore<0.5) 
      return "positive"; 
     else if(averageScore>=0.5) 
      return "positive"; 
     else if(averageScore < 0 && averageScore>=-0.25) 
      return "negative"; 
     else if(averageScore < -0.25 && averageScore>=-0.5) 
      return "negative"; 
     else if(averageScore<=-0.75) 
      return "very negative"; 
     return "neutral"; 
    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
    } 

Répondre

7

tout d'abord commencer par la suppression de tous les "déchets" au premier du fichier (qui comprend la description, instruction etc ..)

Une utilisation possible est de changer SWN3 une rendre la méthode extract en elle un retour Double:

public Double extract(String word) 
{ 
    Double total = new Double(0); 
    if(_dict.get(word+"#n") != null) 
     total = _dict.get(word+"#n") + total; 
    if(_dict.get(word+"#a") != null) 
     total = _dict.get(word+"#a") + total; 
    if(_dict.get(word+"#r") != null) 
     total = _dict.get(word+"#r") + total; 
    if(_dict.get(word+"#v") != null) 
     total = _dict.get(word+"#v") + total; 
    return total; 
} 

Puis, en donnant une chaîne que vous voulez taguer, vous pouvez la diviser pour qu'elle ne contienne que des mots (sans signes et caractères inconnus) et en utilisant le résultat de la méthode extract sur chaque mot, vous pouvez décider quelle est la poids moyen de la chaîne:

String[] words = twit.split("\\s+"); 
double totalScore = 0, averageScore; 
for(String word : words) { 
    word = word.replaceAll("([^a-zA-Z\\s])", ""); 
    if (_sw.extract(word) == null) 
     continue; 
    totalScore += _sw.extract(word); 
} 
verageScore = totalScore; 

if(averageScore>=0.75) 
    return "very positive"; 
else if(averageScore > 0.25 && averageScore<0.5) 
    return "positive"; 
else if(averageScore>=0.5) 
    return "positive"; 
else if(averageScore < 0 && averageScore>=-0.25) 
    return "negative"; 
else if(averageScore < -0.25 && averageScore>=-0.5) 
    return "negative"; 
else if(averageScore<=-0.75) 
    return "very negative"; 
return "neutral"; 

J'ai trouvé ce moyen plus facile et cela fonctionne très bien pour moi.


MISE À JOUR:

J'ai changé _dict-_dict = new HashMap<String, Double>(); donc il aura une clé String et une valeur Double.

Je souhaite remplacer _dict.put(word, sent);_dict.put(word, score);

+0

Salut merci pour la réponse, je ne suis toujours pas clair sur certaines parties. Qu'est-ce que ça veut dire? if (_dict.get (mot + "# r")! = null) # n, # a, # r, # v? Merci! – Belgarion

+1

Si vous regardez la première colonne du fichier, vous remarquerez ces lettres (qui signifie * nom *, * verbe * ..) de sorte que vous devriez couvrir tous les cas. – Maroun

+1

Ah je vois. J'ai encore besoin d'un peu plus d'aide, où mettre mon lien vers mon fichier tweet.csv? C: \ Users \ MyName \ Desktop \ tweets.csv J'ai collé mon code mis à jour ci-dessus, svp n'hésitez pas à le modifier, merci! – Belgarion

0

pour que vous devriez écrire la fonction principale, en qui fournissent le chemin de csv, extrait les mots de celui-ci. puis appelez la fonction d'extraction en envoyant le mot et son pos.

Questions connexes