JL i'dZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd l mZdd l mZdd lmZGd d Zy)z A SentimentAnalyzer is a tool to implement and facilitate Sentiment Analysis tasks using NLTK features and classifiers, especially for teaching and demonstrative purposes. N) defaultdict)accuracy)apply_features)BigramCollocationFinder)BigramAssocMeasures) f_measure) precision)recall)FreqDistceZdZdZddZddZddZddZddejfdZ d Z d Z d Z dd Zd Z ddZy)SentimentAnalyzerzI A Sentiment Analysis tool based on machine learning approaches. Nc:tt|_||_yN)rlistfeat_extractors classifier)selfrs g/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/sentiment/sentiment_analyzer.py__init__zSentimentAnalyzer.__init__!s*40$cg}||xrt|dt}|r|D]\}}|j||S|s|D]}|j||S)a Return all words/tokens from the documents (with duplicates). :param documents: a list of (words, label) tuples. :param labeled: if `True`, assume that each document is represented by a (words, label) tuple: (list(str), str). If `False`, each document is considered as being a simple list of strings: list(str). :rtype: list(str) :return: A list of all words/tokens in `documents`. r) isinstancetupleextend)r documentslabeled all_wordswords _sentiments rrzSentimentAnalyzer.all_words%sx ?CJy|U$CG %. (!z  ' ( " (  ' (rc0t|j||S)a Apply all feature extractor functions to the documents. This is a wrapper around `nltk.classify.util.apply_features`. If `labeled=False`, return featuresets as: [feature_func(doc) for doc in documents] If `labeled=True`, return featuresets as: [(feature_func(tok), label) for (tok, label) in toks] :param documents: a list of documents. `If labeled=True`, the method expects a list of (words, label) tuples. :rtype: LazyMap )rextract_features)rrrs rrz SentimentAnalyzer.apply_features;sd33YHHrctd|D}|j|Dcgc]\}}|||kDr|c}}Scc}}w)a7 Return most common top_n word features. :param words: a list of words/tokens. :param top_n: number of best words/tokens to use, sorted by frequency. :rtype: list(str) :return: A list of `top_n` words/tokens (with no duplicates) sorted by frequency. c3 K|]}|ywr).0words r z7SentimentAnalyzer.unigram_word_feats..Vs&>t&>s )r most_common)rrtop_nmin_frequnigram_feats_freqswfs runigram_word_featsz$SentimentAnalyzer.unigram_word_featsKsS'&>&>>,77> 1"1%0    s?crtj|}|j||j||S)ai Return `top_n` bigram features (using `assoc_measure`). Note that this method is based on bigram collocations measures, and not on simple bigram frequency. :param documents: a list (or iterable) of tokens. :param top_n: number of best words/tokens to use, sorted by association measure. :param assoc_measure: bigram association measure to use as score function. :param min_freq: the minimum number of occurrencies of bigrams to take into consideration. :return: `top_n` ngrams scored by the given association measure. )rfrom_documentsapply_freq_filternbest)rrr)r* assoc_measurefinders rbigram_collocation_featsz*SentimentAnalyzer.bigram_collocation_feats]s3")77 B  *||M511rcf|j|gd}|jj|dS)a  Classify a single instance applying the features that have already been stored in the SentimentAnalyzer. :param instance: a list (or iterable) of tokens. :return: the classification result given by applying the classifier. F)rr)rrclassify)rinstanceinstance_featss rr8zSentimentAnalyzer.classifyrs5,,hZ,G''q(9::rc @|j|j|y)aG Add a new function to extract features from a document. This function will be used in extract_features(). Important: in this step our kwargs are only representing additional parameters, and NOT the document we have to parse. The document will always be the first parameter in the parameter list, and it will be added in the extract_features() function. :param function: the extractor function to add to the list of feature extractors. :param kwargs: additional parameters required by the `function` function. N)rappend)rfunctionkwargss radd_feat_extractorz$SentimentAnalyzer.add_feat_extractor}s X&--f5rci}|jD]0}|j|D] }||fi|} |j2|S)ak Apply extractor functions (and their parameters) to the present document. We pass `document` as the first parameter of the extractor functions. If we want to use the same extractor function multiple times, we have to add it to the extractors with `add_feat_extractor` using multiple sets of parameters (one for each call of the extractor function). :param document: the document that will be passed as argument to the feature extractor functions. :return: A dictionary of populated features extracted from the document. :rtype: dict )rupdate)rdocument all_features extractor param_setfeatss rr!z"SentimentAnalyzer.extract_featuress] -- 'I!11)< 9 !(8i8 9    & 'rc td||fi||_|r|j|j||jS)a Train classifier on the training set, optionally saving the output in the file specified by `save_classifier`. Additional arguments depend on the specific trainer used. For example, a MaxentClassifier can use `max_iter` parameter to specify the number of iterations, while a NaiveBayesClassifier cannot. :param trainer: `train` method of a classifier. E.g.: NaiveBayesClassifier.train :param training_set: the training set to be passed as argument to the classifier `train` method. :param save_classifier: the filename of the file where the classifier will be stored (optional). :param kwargs: additional parameters that will be passed as arguments to the classifier `train` function. :return: A classifier instance trained on the training set. :rtype: zTraining classifier)printr save_file)rtrainer training_setsave_classifierr>s rtrainzSentimentAnalyzer.trains=& #$!,9&9  NN4??O <rctd|tjt|d5}ddl}|j ||ddddy#1swYyxYw)zZ Store `content` in `filename`. Can be used to store a SentimentAnalyzer. Saving)filewbrN)protocol)rHsysstderropenpickledump)rcontentfilename storage_filerWs rrIzSentimentAnalyzer.save_filesL hszz2 (D ! ;\  KKK :  ; ; ;s A  Ac| |j}tdt|jdi}|rt ||} | |d<t t } t t } t } t|D]R\} \}}| j|| |j| |j|}| |j| T| D]Z}|rt| || |}||d|d<|rt| || |}||d|d<|s@t| || |}||d|d<\|r#t|D]}t|d|||S) a0 Evaluate and print classifier performance on the test set. :param test_set: A list of (tokens, label) tuples to use as gold set. :param classifier: a classifier instance (previously trained). :param accuracy: if `True`, evaluate classifier accuracy. :param f_measure: if `True`, evaluate classifier f_measure. :param precision: if `True`, evaluate classifier precision. :param recall: if `True`, evaluate classifier recall. :return: evaluation results. :rtype: dict(str): float z Evaluating z results...Accuracyz Precision []zRecall [z F-measure [z: )rrHtype__name__ eval_accuracyrset enumerateaddr8eval_precision eval_recalleval_f_measuresorted)rtest_setrrrr r verbosemetrics_resultsaccuracy_score gold_results test_resultslabelsirFlabelobservedprecision_score recall_scoref_measure_scoreresults revaluatezSentimentAnalyzer.evaluates,  J D,556kBC *:x@N*8OJ '"3' "3' !*8!4 * A~u JJu    # #A &!**51H  " & &q )  *  JE"0 'e)<#;J+eWA 67*<+> U@ST 7C(5' 34"0 'e)<#;J+eWA 67 J  1 >?6#:";<= >rr)Nr)NTTTTF)r` __module__ __qualname____doc__rrrr.rpmir6r8r?r!rMrIrwr$rrr r sc%,I  & $a?R?V?V2* ; 6(4 ;;rr )rzrT collectionsrnltk.classify.utilrrarnltk.collocationsr nltk.metricsrrrgr rer rfnltk.probabilityr r r$rrrs6  #8-5,44.%ccr