Esempio n. 1
0
def test_chunking_brackets():
    language='english'
    tt = TreeTagger(language=language, path_to_home=treetagger_path)
    phrase = 'What is the airspeed of an (unladen) swallow?'
    sentence = tt.tag(phrase)
    cp = TreeTaggerChunker(language=language, path_to_home=treetagger_path)
    print(cp.parse(sentence))
Esempio n. 2
0
    def __init__(self, products):
        self.username = ''
        self.prodlist = products
        #self.prodlist_itemoid = list(self.prodlist.keys())
        self.prodlist_itemoid = self.add_itemoid()
        self.request = Counter(self.prodlist.keys())
        self.request.subtract(
            self.request
        )  # sottraggo se stesso cosi da avere un dict con keys = nome prodotti, e value=0

        self.tagger = TreeTagger(language='italian')
        self.converter = Converter()

        self.positive_predicates = ['volere', 'aggiungere']
        self.negative_predicates = [
            'rimuovere', 'togliere', 'cancellare', 'eliminare'
        ]
        self.predicates = self.positive_predicates + self.negative_predicates
        self.completings = ['ok']
        self.terminatings = [
            'fine', 'tutto', 'termina', 'annulla', 'annullare'
        ]
        self.id_err = [
            'riconoscimento', 'identità', 'persona', 'utente', 'sono', 'faccia'
        ]
Esempio n. 3
0
def test_chunking_de():
    language='german'
    tt = TreeTagger(language=language, path_to_home=treetagger_path)
    phrase = 'Das Haus hat einen großen hübschen Garten.'
    sentence = tt.tag(phrase)
    cp = TreeTaggerChunker(language=language, path_to_home=treetagger_path)
    print(cp.parse(sentence))
Esempio n. 4
0
    def __init__(self, path_projeto, noticia, legenda, titulo, path, path_dir):
        self.path_projeto = path_projeto
        self.diretorio = path_projeto + path_dir
        self.path_noticia = path_projeto + path
        self.noticia = noticia
        self.noticia_inicial = noticia
        self.legenda = legenda
        self.titulo = titulo
        self.lst_top_substantivos = []
        self.lst_top_entidades_nomeadas = []
        self.total_entidades = 0
        self.tipo_wordNet = ""
        self.lst_EntidadesNomeadas = []
        self.lst_interseccao_entidades = []
        self.lst_top_substantivos_physical = []
        self.lst_top_substantivos_objects = []
        self.lst_diferenca_entidades = []
        self.dict_lematizado = {}
        self.chunker = MWEChunker()

        self.crefdoc = CoreferenceDocument()
        self.snt_tok = []

        PATH_LOCATION = os.path.dirname(os.path.abspath(__file__))
        print(PATH_LOCATION)

        TREE_TAGGER_PATH = PATH_LOCATION + '/TreeTagger'
        print('exportando tree tagger em ', TREE_TAGGER_PATH)
        os.environ["TREETAGGER_HOME"] = TREE_TAGGER_PATH

        self.tree_tagger = TreeTagger(language='english')
def extract_keywords(raw_text,id,language):

    print("Extracting keywords for "+id)

    stemmer = nltk.PorterStemmer()

    # Construct text

    # Tokens

    if language == 'english':
        tokens = nltk.word_tokenize(raw_text)
        # filter undesirable words and format
        words = [w.replace('\'','') for w in tokens if len(w)>=3]
        text = nltk.Text(words)

        tagged_text = nltk.pos_tag(text)

    else:
       tt = TreeTagger(encoding='utf-8',language='french')
       tagged_text =tt.tag(raw_text.replace('\'',' ').replace(u'\u2019',' ').replace(u'\xab',' ').replace(u'\xbb',' '))

    print(tagged_text)

    # detect language using stop words, adapt filtering/stemming technique in function

    # multi-term
    multiterms = []
    for i in range(len(tagged_text)) :
  #      # max length 4 for multi-terms
        for l in range(1,5) :
            if i+l < len(tagged_text) :
                tags = [tagged_text[k] for k in range(i,i+l)]
                #if language == 'english':
                #        print(tags)
		#	print(potential_multi_term(tags,language))
		if potential_multi_term(tags,language) :
                    multistem = []
		    if language == 'english':
			#print(tags)
			#for k in range(i,i+l):
		        #    print(tagged_text[k][0])
			#    print(stemmer.stem(tagged_text[k][0]))
			#    print(stemmer.stem(tagged_text[k][0]).encode('ascii','ignore'))

			multistem = [str.lower(stemmer.stem(tagged_text[k][0]).encode('utf8','ignore')) for k in range(i,i+l)]
                    else :#in case of french or other language, terms are already stemmed by TreeTagger
			multistem=[]
			for k in range(i,i+l):
			    if tagged_text[k][2]!="<unknown>":
			        stem = tagged_text[k][2]
			    else :
			        stem = tagged_text[k][0]
			    multistem.append(str.lower(stem.encode('utf8','ignore')))
		    #multistem.sort(key=str.lower)
                    multiterms.append(multistem)

    return multiterms
def getFeatureVecFromPOS(oneLine, lang, n_gram_range, ngram_vec):
    clean_train_reviews = review_to_words(oneLine, lang)
    tt = TreeTagger(encoding='latin-1', language=lang)
    train_reviews_pos_tags = []

    train_reviews_pos_tags = tt.tag(clean_train_reviews)
    a = [col[1] for col in train_reviews_pos_tags]
    pos_line = " ".join(a)
    X = ngram_vec.transform(pos_line).toarray()
    return X
def getFeatureVecFromPOS(oneLine, lang, n_gram_range, ngram_vec):
	clean_train_reviews = review_to_words( oneLine, lang )
	tt = TreeTagger(encoding='latin-1',language=lang)
	train_reviews_pos_tags = []
	
	train_reviews_pos_tags = tt.tag(clean_train_reviews)
	a = [col[1] for col in train_reviews_pos_tags]
	pos_line = " ".join(a)
	X = ngram_vec.transform(pos_line).toarray()
	return X
def pos_tag_sents(tokenized_sents):
    from treetagger import TreeTagger

    tagged_sents = []
    for i, s in enumerate(tokenized_sents):
        tt = TreeTagger(language='german')
        tags = [t for t in tt.tag(s) if len(t) > 1]
        tags = [tuple(tag + ["_", ""]) for tag in tags]
        tagged_sents.append(tags)
    return tagged_sents
Esempio n. 9
0
def login():

    text = request.form["text"]

    verb = "empty"
    verb_added = False
    noun = "empty"
    noun_added = False
    arguments = []
    command = "empty"
    encoded_tags = []
    encoded_text_with_tags = []
    plural = False
    reload(sys)
    sys.setdefaultencoding('utf8')
    tt_pl = TreeTagger(
        path_to_treetagger='/Users/kasper/Development/Python/SmartTerminal/',
        language='polish')
    tags = tt_pl.tag(text)
    for tag in tags:

        if set(tag[1].split(":")) & set(data.VERB):
            verb = tag[2]
            verb_added = True
        elif verb_added and not set(tag[1].split(":")) & set(data.NOT_NOUN):
            if "pl" in tag[1]:
                plural = True
            noun = tag[2]
            noun_added = True
            verb_added = False
        elif noun_added and not set(tag[1].split(":")) & set(data.NOT_NOUN):
            arguments.append(tag[0])

    if plural:
        for argument in arguments:
            command = data.actions[verb][noun] + argument
            os.system(command)

    else:
        if not len(arguments) == 0:
            command = data.actions[verb][noun] + arguments[0]
        else:
            command = data.actions[verb][noun]
        os.system(command)

    if text:
        return jsonify({'result': 'OK'})
    else:
        return jsonify({'result': 'BAD'})
 def __init__(self, language):
     "Initialize NegationDetector with a specific language."
     self.this_dir, self.this_filename = os.path.split(__file__)
     self.language = language
     self._tokenizers = {'dutch': 'tokenizers/punkt/dutch.pickle',
                       'english': '',
                       'spanish': 'tokenizers/punkt/spanish.pickle'}
     self.json_files = {'english': 'english_negations.json'}
     
     # Check if the entered language is supported.
     try:
         assert self.language in self.json_files
     except AssertionError:
         raise NotImplementedError('Unsupported language!')
     
     self.json_path = os.path.join(self.this_dir, 'data', self.json_files[self.language])
     with open(self.json_path) as f:
         # Load the lexicon.
         self.lexicon = {kind: set(words) for kind, words in json.load(f).items()}
     self.tagger = TreeTagger(language=self.language)
     
     if language == 'english':
         # English is the standard in NLTK
         from nltk.tokenize import sent_tokenize
         self.sent_tokenize = sent_tokenize
     else:
         # Other languages have to be loaded using Pickle.
         pickle_path = self.tokenizers[language]
         self.sent_tokenize = nltk.data.load(pickle_path).tokenize
Esempio n. 11
0
 def get_treetagger_postagger(self, language='en'):
     if not self.__has_key(self.__treetaggers, language):
         dirname, filename = os.path.split(os.path.abspath(__file__))
         self.__treetaggers[language] = TreeTagger(
             language=language,
             path_to_home=os.path.join(dirname, 'treetagger', 'cmd'))
     return self.__treetaggers[language]
Esempio n. 12
0
def tagLang(langs):
    global tagDictMap, taggerMap
    if "fr" in langs:
        frTagDict = convertTags('fr-treetagger.map')
        frTagger = TreeTagger(encoding='utf-8', language='french')
        tagDictMap['fr'] = frTagDict
        taggerMap['fr'] = frTagger
    if "sl" in langs:
        slTagDict = convertTags('sl-treetagger.map')
        slTagger = TreeTagger(encoding='utf-8', language='slovenian')
        tagDictMap['sl'] = slTagDict
        taggerMap['sl'] = slTagger
    if "de" in langs:
        deTagDict = convertTags('de-tiger.map')
        deTagger = TreeTagger(encoding='utf-8', language='german')
        tagDictMap['de'] = deTagDict
        taggerMap['de'] = deTagger
    if "it" in langs:
        itTagDict = convertTags('it-treetagger.map')
        itTagger = TreeTagger(encoding='utf-8', language='italian')
        tagDictMap['it'] = itTagDict
        taggerMap['it'] = itTagger
    if "pl" in langs:
        plTagDict = convertTags('pl-treetagger.map')
        plTagger = TreeTagger(encoding='utf-8', language='polish')
        tagDictMap['pl'] = plTagDict
        taggerMap['pl'] = plTagger
    if "sk" in langs:
        skTagDict = convertTags('sk-treetagger.map')
        skTagger = TreeTagger(encoding='utf-8', language='slovak')
        tagDictMap['sk'] = skTagDict
        taggerMap['sk'] = skTagger
    if "es" in langs:
        esTagDict = convertTags('es-treetagger.map')
        esTagger = TreeTagger(encoding='utf-8', language='spanish')
        tagDictMap['es'] = esTagDict
        taggerMap['es'] = esTagger
    if "nl" in langs:
        nlTagDict = convertTags('nl-treetagger.map')
        nlTagger = TreeTagger(encoding='utf-8', language='dutch')
        tagDictMap['nl'] = nlTagDict
        taggerMap['nl'] = nlTagger
    engTagger = TreeTagger(encoding='utf-8', language='english')
    taggerMap['en'] = engTagger
    engTagDict = convertTags('en-ptb.map')
    tagDictMap['en'] = engTagDict
    output = open('tagged.all', 'w')
    errors = open('errors.txt', 'w')
    numLines = 0
Esempio n. 13
0
def lemmatize_data(data):
    tt = TreeTagger(language='english')
    lemm_data = {"abstract": []}
    count = 0
    for index, row in data.iterrows():
        print(count)
        count += 1
        abstract = ''
        if len(row['abstract']) != 0:
            for word, _, lemma in tt.tag(row['abstract']):
                if lemma == '<unknown>':
                    abstract += word + ' '
                elif "|" in lemma:
                    parts = lemma.split("|")
                    abstract += min(parts, key=len) + ' '
                else:
                    abstract += lemma + ' '
        lemm_data['abstract'].append(abstract)
    return pd.DataFrame(lemm_data)
    def getOtherError(self):

        tt = TreeTagger(language='english')
        #getting the Stanford parse list
        testSentence = " ".join(self.words)
        StanParserLst = []
        StanParserLst = self.synt
        outLst = tt.tag(testSentence)
        tagLst = []

        #aligning the treetagger POS tags to match the stanford parser tags and adding changed tags to tagLst
        tagChangeDic = {
            'NP': 'NNP',
            'NPS': 'NNPS',
            'PP': 'PRP',
            'SENT': '.',
            '(': '-LRB-',
            ')': '-RRB-'
        }

        for word, tag, form in outLst:
            if tag in tagChangeDic.keys():
                tagLst.append(tagChangeDic.get(tag))
            else:
                tagLst.append(tag)

        #checking at each index if there is a mismatch in tagging between stanford parser and treetagger tags
        if len(self.synt) == len(tagLst):
            SPlst = []
            TTlst = []
            i = 0
            while (i < len(self.synt)):

                if self.synt[i] != tagLst[i]:

                    objOthererr = errDef.ErrorDef("OTHER")
                    retVal = objOthererr.checkOther(i, self.synt[i], self)
                    print(retVal)
                    if retVal != 0:
                        self.sentDetailobj.objLstProblems.AddToProblemListTypewise(
                            "OTHER", retVal)
                i += 1
def	getFeatureVecFromPOS(fileName, lang, n_gram_range):
	train = pd.read_csv(fileName, header=0, delimiter="\t", quoting=1)
	num_text = train["text"].size

	clean_train_reviews = []
# 	print "Looping through all text.\n" 

	for i in xrange( 0, num_text):
		clean_train_reviews.append( review_to_words( train["text"][i], lang ) )
	
	tt = TreeTagger(encoding='latin-1',language=lang)
	train_reviews_pos_tags = []
	
	for line in clean_train_reviews:
		a = tt.tag(line)
		a = [col[1] for col in a]
		pos_line = " ".join(a)
		train_reviews_pos_tags.append(pos_line)

	ngram_vectorizer = CountVectorizer(ngram_range=n_gram_range, min_df=1)
	X = ngram_vectorizer.fit_transform(train_reviews_pos_tags).toarray()
	return X, ngram_vectorizer
Esempio n. 16
0
def tokenize(text):
	'''
		Tokenize and lemmatize a text using tree tagger

		Arguments
			- text: string containing the the text
		
		Returns
			- tokens: list of all the lemmatized tokens

		NOTE : tree tagger tag function returns
		a tuple (token, tag, lemmatized_token)
	'''
	tree = TreeTagger()

	text = text.lower()

	tokens = [t[2] for t in tree.tag(text) if len(t) == 3 and t[2] != '<unknown>' and t[1] != 'NUM' and t[1] != 'PUN']
	tokens = [t for t in tokens if len(t) > 2]
	tokens = [t for t in tokens if t not in STOPWORDS]

	return tokens
    def getPOS(self, text):

        tt = TreeTagger(language='polish')
        sentences = tt.tag(text)

        pos_sentences = []
        sent = []
        for w in sentences:
            if len(w) < 3:
                continue
            if w[1].find(':') == -1:
                tag = w[1]
            else:
                tag = w[1].split(':')[0]
            if tag == 'SENT':
                pos_sentences.append(sent)
                sent = []
            else:
                sent += [tag]
        self.pos_sentences = pos_sentences

        return self.pos_sentences
def getFeatureVecFromPOS(fileName, lang, n_gram_range):
    train = pd.read_csv(fileName, header=0, delimiter="\t", quoting=1)
    num_text = train["text"].size

    clean_train_reviews = []
    # 	print "Looping through all text.\n"

    for i in xrange(0, num_text):
        clean_train_reviews.append(review_to_words(train["text"][i], lang))

    tt = TreeTagger(encoding='latin-1', language=lang)
    train_reviews_pos_tags = []

    for line in clean_train_reviews:
        a = tt.tag(line)
        a = [col[1] for col in a]
        pos_line = " ".join(a)
        train_reviews_pos_tags.append(pos_line)

    ngram_vectorizer = CountVectorizer(ngram_range=n_gram_range, min_df=1)
    X = ngram_vectorizer.fit_transform(train_reviews_pos_tags).toarray()
    return X, ngram_vectorizer
Esempio n. 19
0
def lemmatize_data(data):
    tt = TreeTagger(language='english')
    res = []
    count = 0
    for index, row in data.iterrows():
        count += 1
        eprint(count)
        abstract = []
        for elem in tt.tag(row[' Abstract ']):
            lemma = elem[2]
            if lemma == '<unknown>':
                abstract.append(elem[0])
            elif len(lemma.split("|")) == 2:
                parts = lemma.split("|")
                if len(parts[0]) < len(parts[1]):
                    abstract.append(parts[0])
                else:
                    abstract.append(parts[1])
            else:
                abstract.append(lemma)
        if len(abstract) > 0:
            res.append(' '.join(word for word in abstract))
    return res
Esempio n. 20
0
def postags(data, text_column="reponse", lang="french"):
    """
    Return TreeTagger Part-Of-Speech outputs for large corpus. 
    
    Parameters
    ----------
    texts : list of str
        corpus
    lang : str, optional
        {french, spanish, english, ...}, by default "french"
    nb_split : int, optional
        number of text send to TreeTagger at each loop, by default 50
    """
    tree_tagger = TreeTagger(language=lang)
    res = tree_tagger.tag("\n##############END\n".join(
        data[text_column].values))
    res = [r for r in res if len(r) == 3]
    res = np.asarray(res)
    indexes = np.where(res[:, 0] == "##############END")[0]
    pos_tag_data = np.asarray(
        [parse_output(i[1:]) for i in np.split(res, indexes)])
    data["pos_tag"] = pos_tag_data
    return data
Esempio n. 21
0
# Read the rules from the file
rules = []
for line in open("dict/rules.tsv", "r"):
    line = line.replace("\n", "")
    line = line.replace("\r", "")
    rules.append(line)

# Build the parser, and parse rules
parser = yacc.yacc()
print("\nLoading rules:")
for rule in rules:
    result = parser.parse(rule)
    print("\tRule parsed succesfully: %s" % rule)

tt = TreeTagger(encoding='latin-1', language=language)
sentiwordnet = SentiWordnet()
to_wordnet = TreetaggerToWordnet()

# Init Tornado web server
application = tornado.web.Application([
    (r"/", MainHandler,
     dict(rules=compiled_rules,
          to_wordnet=to_wordnet,
          sentiwordnet=sentiwordnet,
          tt=tt,
          stopwords=stopwords,
          chunks=chunks,
          language=language)),
])
Esempio n. 22
0
#encoding: utf-8
from treetagger import TreeTagger
tt = TreeTagger(language='english', encoding='latin-1')
tagged_sent = tt.tag(
    'What is the airspeed of an unladen swallow? And what about the € sign?')
print tagged_sent
Esempio n. 23
0
#! /usr/bin/python

from treetagger import TreeTagger
from collections import defaultdict

import csv
import re
import json
import sys
import random
import math

k = 8
saco_de_gato = {}
tt_pt = TreeTagger(language = 'portuguese2')
palavra_morfologia = {}
pattern = re.compile("(^PUNCT.*$|^AUX.*$|^PRON.*$|^DET.*$|^ADP.*$|^SCONJ.*$)")

def sort_second(value):
    return value[1]

# Ler csv
# ID;PERGUNTAS;RESPOSTAS;CLASSES;;
with open(sys.argv[1], 'r', encoding='utf-8', newline='') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter = ';')
    for row in csv_reader:
        pergunta = {}
        pergunta['id'] = row[0].strip()
        pergunta['pergunta'] = row[1].strip()
        pergunta['resposta'] = row[2].strip()
        pergunta['classe'] = row[3].strip()
Esempio n. 24
0
class Bot():
    """
    Bot class that manages the dialog between the user and the system.
    Attributes:
        username                current users name
        prodlist                vending machine products data
        prodlist_itemoid        vending machine products data splitted by spaces for matching in check_for_products
        request                 Counter Dict object representing users bill
        tagger                  Object from TreeTagger Library
        converter               Instance of Converter class
        predicates              List of predicates that should be recognized from what user say
        positive_predicates     Sub-list of positive predicates
        negative_predicates     Sub-list of negative predicates
        completings             List of words that should end conversation positively
        terminatings            List of words that should remove items
        id_err                  List of key words that should trigger face recognition

    """
    def __init__(self, products):
        self.username = ''
        self.prodlist = products
        #self.prodlist_itemoid = list(self.prodlist.keys())
        self.prodlist_itemoid = self.add_itemoid()
        self.request = Counter(self.prodlist.keys())
        self.request.subtract(
            self.request
        )  # sottraggo se stesso cosi da avere un dict con keys = nome prodotti, e value=0

        self.tagger = TreeTagger(language='italian')
        self.converter = Converter()

        self.positive_predicates = ['volere', 'aggiungere']
        self.negative_predicates = [
            'rimuovere', 'togliere', 'cancellare', 'eliminare'
        ]
        self.predicates = self.positive_predicates + self.negative_predicates
        self.completings = ['ok']
        self.terminatings = [
            'fine', 'tutto', 'termina', 'annulla', 'annullare'
        ]
        self.id_err = [
            'riconoscimento', 'identità', 'persona', 'utente', 'sono', 'faccia'
        ]

    def set_user_name(self, name):
        """
        Method to set the user name

        Args:
            name     the user name
        """
        self.username = name
        print(self.username)

    def add_itemoid(self):
        """
        Method to fill prodlist_itemoid

        """
        products = []
        for item in self.prodlist:
            for itemoid in item.split():
                products.append(itemoid)
        return products

    def check_id_error(self, userask):
        """
        Method to check if user said a word contained in id_err

        Args:
            userask     what the user said
        """
        for word in userask.split():
            if word.lower() in self.id_err:
                return True
        return False

    def check_for_completings(self, userask):
        """
        Method to check if the user said a word contained in completings

        Args:
            userask     what the user said
        """
        for word in userask.split():
            if word in self.completings:
                return True
        return False

    def check_for_terminatings(self, userask):
        """
        Method to check if the user said a word contained in terminatings

        Args:
            userask     what the user said
        """
        for word in userask.split():
            if word in self.terminatings:
                return True
        return False

    def check_for_products(self, sentence):
        """
        Method to check if the user said a word contained in prodlist_itemoid. 

        Args:
            userask     what the user said
        """
        for prod in self.prodlist_itemoid:
            if prod in sentence:
                return True
        return False

    def check_itemoid(self, item):
        """
        Once the phrase is POS-tagged, replace each word withe the simplified version of it (checking its existance).

        Args:
            item     the word from what user asked to be replaced
        """
        if item[2] == '<unknown>':
            if item[0] == 'coca-cole' or item[0] == 'cocacola' or item[
                    0] == 'cocacole' or item[0] == 'Coca Cola':
                return 'coca-cola'
            else:
                return item[0]
        elif item[2] == '@card@':
            return item[0]
        elif '|' in item[2]:
            splitted = item[2].split('|')
            return splitted[0]
        else:
            if item[0] == 'arachidi':
                return 'arachidi'
            else:
                return ''

    def get_predicates(self, phrase):
        """
        Method to get predicate from a phrase

        Args:
            phrase     the phrase where to search for predicates
        """
        pred = []
        for i in self.predicates:
            if i in phrase:
                pred.append(i)
        return pred

    def contains_predicate(self, phrase):
        """
        Method to get the presence of predicate in a phrase

        Args:
            phrase     the phrase where to search for predicates
        """
        pred = self.get_predicates(phrase)
        if len(pred) == 0:
            return False
        else:
            return True

    def set_predicate(self, phrase):
        """
        Method to set a predicate in a phrase. If absent or more than one, force a negative_predicate. 
        Es. "voglio togliere un acqua" -> "rimuovere un acqua"

        Args:
            phrase     the phrase where to put the predicate
        """
        if len(self.get_predicates(phrase)) == 1:
            return phrase
        querywords = phrase.split()
        resultwords = [
            word for word in querywords if word.lower() not in self.predicates
        ]
        result = ' '.join(resultwords)
        result = 'rimuovere ' + result
        return result

    def set_request_kind(self, list_of_subphrase):
        """
        Given a list_of_subphrases, check if the first item in lisr_of_subphrases has a predicate, if no predicate is found in it,
        set a positive predicate. The we assign at each element with no predicate, the predicate of the previous element.

        Args:
            list_of_subphrases     the list containing phrases as elements
        """
        if self.contains_predicate(list_of_subphrase[0]) == False:
            list_of_subphrase[0] = 'volere ' + list_of_subphrase[0]
        else:
            list_of_subphrase[0] = self.set_predicate(list_of_subphrase[0])

        for i, phrase in enumerate(list_of_subphrase[1:len(list_of_subphrase)],
                                   start=1):
            if self.contains_predicate(phrase) == False:
                pr = " ".join(
                    str(x)
                    for x in self.get_predicates(list_of_subphrase[i - 1]))
                list_of_subphrase[i] = pr + ' ' + list_of_subphrase[i]
            else:
                list_of_subphrase[i] = self.set_predicate(list_of_subphrase[i])
        return list_of_subphrase

    def get_prod(self, phrase):
        """
        Method to get a prod name from a phrase

        Args:
            phrase     a string
        """
        for prod in self.prodlist:
            if prod in phrase:
                return prod
        return False

    def get_amount(self, phrase):
        """
        Method to get the amount  from a phrase

        Args:
            phrase     a string
        """
        for word in phrase.split():
            if word.isdigit():
                return int(word)
        return None

    def get_all_products(self, phrase):
        """
        Method to get all the products from a phrase

        Args:
            phrase     a string
        """
        prod = []
        for item in self.prodlist:
            if item in phrase:
                prod.append(item)
        return prod

    def correct_no_amount(self, list_of_subphrase):
        """
        Method to correct no amount cases in list_of_subphrases

        Es. ['voglio acqua', 'coca-cola'] -> ['voglio 1 acqua', '1 coca-cola']

        Args:
            list_of_subphrases     the list containing phrases as elements
        """
        new_list_subphrase = []
        for phrase in list_of_subphrase:
            if self.get_amount(phrase) is None:
                phrase = '1 ' + phrase
            new_list_subphrase.append(phrase)
        return new_list_subphrase

    def correct_multiple_prod(self, list_of_subphrase):
        """
        Method to set the user name

        Args:
            name     the user name
        """
        # corregge casi come ['voglio 1 acqua 1 coca-cola'] -> ['voglio 1 acqua', '1 coca-cola']
        new_list = []
        final_list = []
        for phrase in list_of_subphrase:
            in_list = []
            count = 0
            splitted_phrase = phrase.split()
            splitted_phrase.extend('1')
            for idx, word in enumerate(splitted_phrase):
                if word.isdigit():
                    count += 1
                    if count > 1:
                        length = sum(len(x) for x in in_list)
                        in_list.append(phrase.split()[length:idx])
            new_list.extend(in_list)
        for element in new_list:
            sub_phrase = ' '.join(element)
            final_list.append(sub_phrase)
        return final_list

    def correct_ultra_no_amount(self, list_of_subphrase):
        """
        Method to correct another case of no_amount

        Args:
            list_of_subphrases     the list containing phrases as elements
        """
        new_list = []
        for phrase in list_of_subphrase:
            items = {}
            for item in self.prodlist:
                if item in phrase:
                    idx = phrase.find(item)
                    items[idx] = item
            if len(list(items.keys())) > 1:
                start_idx = 0
                keys = sorted(items.keys())
                for item_idx in keys:
                    idx = item_idx + len(items[item_idx])
                    new_list.append(phrase[start_idx:idx])
                    start_idx = idx
            else:
                new_list.append(phrase)
        return new_list

    def parse_input(self, usersaid):
        """
        Method to parse what user said

        Args:
            usersaid     what the user said
        """
        p = self.tagger.tag(usersaid)
        # faccio una lista degli elementi parsati per semplificare la frase
        seq_phrase = []
        for item in p:
            res = self.check_itemoid(item)
            if item[2] == 'un' or item[2] == 'una':
                seq_phrase.append('uno')
            elif item[0] in self.prodlist_itemoid:
                seq_phrase.append(item[0])
            elif res == '':
                seq_phrase.append(item[2])
            else:
                seq_phrase.append(res)

        # ricostruisco una frase convertendo numeri scritti in lettere in numeri
        parsed_phrase = ' '.join(seq_phrase)

        print("parsed = " + parsed_phrase)
        # divido quando c'è una "e", pesumibilmente ogni sottofrase ha un significato diverso
        list_of_subphrase = parsed_phrase.split(' e ')
        print("list_of_subphrase = ")
        print(list_of_subphrase)

        list_of_subphrase = self.correct_no_amount(list_of_subphrase)
        print(list_of_subphrase)

        list_of_subphrase = self.correct_multiple_prod(list_of_subphrase)
        print(list_of_subphrase)

        list_of_subphrase = self.correct_ultra_no_amount(list_of_subphrase)
        print(list_of_subphrase)

        list_of_subphrase = self.correct_no_amount(list_of_subphrase)
        print(list_of_subphrase)

        corrected_subphrase = self.set_request_kind(list_of_subphrase)

        print(corrected_subphrase)
        return (corrected_subphrase)

    def update_request(self, userask):
        """
        parse the input and update request accordingly

        Args:
            userask     what the user asked
        """
        list_of_subphrases = self.parse_input(userask)
        for phrase in list_of_subphrases:
            pred = self.get_predicates(phrase)
            amount = self.get_amount(phrase)
            prod = self.get_prod(phrase)
            if pred[0] in self.positive_predicates and prod in self.prodlist:
                self.request[prod] += amount
            elif pred[0] in self.negative_predicates and prod in self.prodlist:
                self.request[prod] -= amount
                if self.request[prod] < 0:
                    self.request[prod] = 0

    def check_if_request_is_not_empty(self):
        """
        Return True if the request dict is not empty.  

        """
        for prod in self.request:
            if self.request[prod] > 0:
                return True
        return False

    def replace_itemoid(self, userask):
        """
        Method to replace itemoid with preper item names using edit distance

        Args:
            userask     what the user asked
        """
        word_list = userask.split()
        for word in word_list:
            if len(word) > 2:
                min_item = word
                min_dist = 1000
                for item in self.prodlist_itemoid:
                    dist = editdistance.eval(word, item)
                    if dist < 3:
                        if dist < min_dist:
                            min_dist = dist
                            min_item = item
                userask = userask.replace(word, min_item)
        return userask

    def replace_numbers(self, userask):
        """
        Method to replace string number with digits

        Args:
            userask     what the user asked
        """
        converted_phrase = ''
        for item in userask.split():
            if item == 'un' or item == 'una':
                item = 'uno'
            if item != 'e':
                num = self.converter.let2num(item)
                if num.isdigit():
                    converted_phrase += num + ' '
                else:
                    converted_phrase += item + ' '
            else:
                converted_phrase += item + ' '
        return converted_phrase

    def reply(self, userask):
        """
        Method to reply to the user

        Args:
            userask     what the user asked
        """

        userask = userask.replace("'", " ").replace(" alla ", " ").replace(
            " al ", " ").replace(" ai ", " ").replace(" di ", " ").replace(
                "coca cola", "coca-cola").replace("coca cole", "coca-cola")

        list_userask = regexp.split('(\d+)', userask)

        userask = ' '.join(list_userask)
        print(userask)

        userask = self.replace_numbers(userask)
        print(userask)
        userask = self.replace_itemoid(userask)
        print(userask)

        if userask.lower() == "impossibile capire" or userask.lower(
        ) == 'richieste speech-to-text terminate':
            reply = 'Scusa non ho capito. Ripeti perfavore.'
            print(reply)
            return False, reply, self.request
        elif self.check_for_terminatings(userask) or userask == "no":
            reply = 'Ciao ' + str(self.username)
            return None, reply, self.request
        elif self.check_for_completings(userask):
            if self.check_if_request_is_not_empty():
                reply = 'Addebito richiesta effettuato. Ciao ' + str(
                    self.username)
                return True, reply, self.request
            else:
                reply = 'Ma ' + str(
                    self.username
                ) + ' ancora non mi hai chiesto nessun prodotto!'
                return False, reply, self.request

            # use API to complete request for the amount
        elif self.check_id_error(userask):
            reply = 'Mi dispiace molto non averti riconosciuto, riproviamo.'
            return None, reply, self.request
        elif self.check_for_products(userask):
            print("Prodotto rilevato, inizio parsing...")
            self.update_request(userask)
            if sum(self.request.values()) == 0:
                reply = 'Non hai prodotti nel carrello, cosa ti serve?'
                return False, reply, self.request
            cost = 0
            missing = []
            ok = 0
            reply1 = ''
            for prod in self.request:
                if self.request[prod] > 0:
                    if int(self.prodlist[prod][1]) >= self.request[prod]:
                        ok += 1
                        reply1 = reply1 + str(
                            self.request[prod]) + ' ' + prod + ', '
                        cost += float(
                            self.prodlist[prod][0]) * self.request[prod]
                    else:
                        missing.append(prod)
                        self.request[prod] = int(self.prodlist[prod][1])
                        if self.request[prod] != 0:
                            ok += 1
                            reply1 = reply1 + str(
                                self.request[prod]) + ' ' + prod + ', '
                            cost += float(
                                self.prodlist[prod][0]) * self.request[prod]
            cost = float("{0:.2f}".format(cost))
            re = ''
            if ok >= len(missing):
                reply3 = 'al prezzo di ' + str(cost) + ' € ?'
                re = 'Quindi vuoi ' + reply1 + reply3
            reply2 = ''
            if len(missing) > 1:
                reply2 += ' Mi dispiace ma '
                for el in missing:
                    reply2 += el + ', '
                reply2 += 'non sono disponibili nelle quantità richieste. Ho inserito le disponibili.'
            elif len(missing) == 1:
                reply2 += ' Mi dispiace ma ' + missing[
                    0] + ' non è disponibile nella quantità richiesta. Ho inserito la quantità disponibile.'

            reply = re + reply2
            if sum(self.request.values()) != 0:
                reply += ' Dì ok per addebitare, o continua a modificare la richiesta.'
            else:
                reply += " Vuoi qualcos'altro ?"
            print(self.request)
            print(reply)
            return False, reply, self.request
        else:
            reply = 'Scusa non ho capito. Ripeti perfavore.'
            print(reply)
            return False, reply, self.request
Esempio n. 25
0
 def test_language(language, phrase):
     tt = TreeTagger(language=language, path_to_home=treetagger_path)
     return tt.tag(phrase)
Esempio n. 26
0
def get_data():
    debTime = time.time()
    df = pd.read_csv(data_path + 'csvTweets.csv')
    cols_to_keep = ['sentiment', 'longitude', 'latitude', 'text']
    df_clean = df[cols_to_keep].dropna()
    lista = []
    j = 0
    liststop = []
    listval = []
    while j < len(df.text):
        tt = TreeTagger(language='english')
        lis = tt.tag(str(df.text[j]).lower())
        for i in lis:
            if ('NN' in i[1]) or ('NP' in i[1]) or ('JJ' in i[1]) or (
                    'VB' in i[1]) or ('#' in i[0]) and (len(i[0]) > 3):
                if i[0] not in stop:
                    if "#" in i[0]:
                        i[0] = i[0].replace("#", "")
                    if "." in i[0]:
                        i[0] = i[0].replace(".", "")
                    lis = []
                    if "-" in i[0]:
                        lis = i[0].split("-")
                        if "" in lis:
                            lis.remove("")
                        i[0] = ' '.join(lis)
                    if "_" in i[0]:
                        lis = i[0].split("_")
                        if "" in lis:
                            lis.remove("")
                        i[0] = ' '.join(lis)
                    inc = 1
                    for letter in i[0]:
                        if not letter in "abcdefghijklmnopqrstuvwxyz ":
                            inc = 0
                    if (inc != 0) and (len(i[0]) > 3):
                        if i[0] in liststop:
                            listval[liststop.index(
                                i[0])] = listval[liststop.index(i[0])] + 1
                        else:
                            listval.append(1)
                            liststop.append(i[0])
        j = j + 1
    js = []
    j = 0
    lenval = len(listval)
    pod = 0
    kickval = ""
    kickstop = ""
    while j < lenval:
        pod = listval.index(max(listval))
        kickval = listval.pop(pod)
        kickstop = liststop.pop(pod)
        js = [kickstop, kickval]
        listm.append(js)
        j = j + 1
    duree = time.time() - debTime
    print "\n"
    print "   @--- Overhead /data socket : "+\
    str(duree)+" seconds ---@"
    print "\n"
    return df_clean.to_json(orient='records')
Esempio n. 27
0
def computeSemanticSimilarityFeatures(sentence1, sentence2):
    features = [0] * 9

    if (sentence1 + sentence2) not in semanticsimilarity_lookuptable:
        def prepareSentence(sentence):
            return sentence.replace('-', ' ').replace('$', ' ')

        tt = TreeTagger(language='english')
        tags1 = [a for a in tt.tag(prepareSentence(sentence1)) if len(a) > 1]
        tags2 = [a for a in tt.tag(prepareSentence(sentence2)) if len(a) > 1]

        semanticsimilarity_lookuptable[sentence1 + sentence2] = [tags1, tags2]

    tags1 = copy.deepcopy(semanticsimilarity_lookuptable[sentence1 + sentence2][0])
    tags2 = copy.deepcopy(semanticsimilarity_lookuptable[sentence1 + sentence2][1])

    # Feature: noun/web semantic similarity
    # Get Synonym set
    def synSet(tags):
        for word in tags:
            # Only compare Nouns or Verbs
            # Python does not have short circuit operators, wtf?!
            if (word[1][0] != 'N' if len(word[1]) >= 1 else 1) and (word[1][:2] != 'VV' if len(word[1]) >= 2 else 1):
                continue

            word.append(wordnet.synsets(word[2]))

    synSet(tags=tags1)
    synSet(tags=tags2)

    simsMaxNoun = []
    simsAvgNoun = []
    simsMaxVerb = []
    simsAvgVerb = []

    for word1, word2 in product(tags1, tags2):
        type1 = word1[1]
        type2 = word2[1]

        if (type1[0] != 'N' and type1[:2] != 'VV') or type1 != type2:
            continue

        similarityMax = 0
        similarityAvg = 0
        if word1[2] == word2[2]:
            similarityAvg = 1
            similarityMax = 1
        else:
            for sense1, sense2 in product(word1[3], word2[3]):
                sim = wordnet.wup_similarity(sense1, sense2)
                similarityMax = max(similarityMax, sim)
                similarityAvg += sim if sim is not None else 0

        if type1[0] != 'N':
            simsMaxNoun.append(similarityMax)
            simsAvgNoun.append(similarityAvg / (len(word1[3]) + len(word2[3])) if len(word1[3]) + len(word2[3]) > 0 else 0)
        else:
            simsMaxVerb.append(similarityMax)
            simsAvgVerb.append(similarityAvg / (len(word1[3]) + len(word2[3])) if len(word1[3]) + len(word2[3]) > 0 else 0)


    features[0] = np.sum(simsMaxNoun) / len(simsMaxNoun) if len(simsMaxNoun) > 0 else 0
    features[1] = np.sum(simsAvgNoun) / len(simsAvgNoun) if len(simsAvgNoun) > 0 else 0

    features[2] = np.sum(simsMaxVerb) / len(simsMaxVerb) if len(simsMaxVerb) > 0 else 0
    features[3] = np.sum(simsAvgVerb) / len(simsAvgVerb) if len(simsAvgVerb) > 0 else 0

    # Feature: Cardinal number similarity
    def findCardinals(tags):
        cardinals = []
        for index, word1 in enumerate(tags):
            if word1[1] == 'CD':
                # is "more", "over" or "above" before?
                before = [a[0] for a in tags[max(index-2, 0):index]]

                try:
                    val = float(word1[0])
                except ValueError:
                    val = t2i.text2int(word1[0])

                maxValue = minValue = val

                if ("more" in before) or ("over" in before) or ("above" in before) or ("greater" in before):
                    maxValue = sys.maxint
                    minValue += 1
                elif ("less" in before) or ("under" in before) or ("below" in before) or ("smaller" in before):
                    minValue = -sys.maxint - 1
                    maxValue -= 1

                cardinals.append([minValue, maxValue])
        return cardinals

    cardinals1 = findCardinals(tags=tags1)
    cardinals2 = findCardinals(tags=tags2)

    def countCDMatches(cardinals1, cardinals2):
        count = 0
        for cd1 in cardinals1:
            for cd2 in cardinals2:
                if cd1[0] == cd2[0] and cd1[1] == cd2[1]:
                    count += 1
                    break
        return count

    features[4] = (countCDMatches(cardinals1, cardinals2) + countCDMatches(cardinals2, cardinals1)) / (len(cardinals1) + len(cardinals2)) if len(cardinals1) + len(cardinals2) > 0 else 1
    #features[2] = countCDMatches(cardinals1, cardinals2) / len(cardinals1) if len(cardinals1) > 0 else 1
    #features[3] = countCDMatches(cardinals2, cardinals1) / len(cardinals2) if len(cardinals2) > 0 else 1


    # Feature: Proper Name
    def findProperNouns(tags):
        nouns = []
        for word in tags:
            if word[1] == 'NPS':
                nouns.append(word[0])
        return nouns

    def countNounMatches(nouns1, nouns2):
        count = 0
        for noun1 in nouns1:
            for noun2 in nouns2:
                if noun1 == noun2:
                    count += 1
                    break
        return count

    nouns1 = findProperNouns(tags1)
    nouns2 = findProperNouns(tags2)

    features[5] = (countNounMatches(nouns1, nouns2) + countNounMatches(nouns2, nouns1)) / (len(nouns1) + len(nouns2)) if len(nouns1) + len(nouns2) > 0 else 1
    # features[4] = countNounMatches(nouns1, nouns2) / len(nouns1) if len(nouns1) > 0 else 1
    # features[5] = countNounMatches(nouns2, nouns1) / len(nouns2) if len(nouns2) > 0 else 1

    # Feature: Word2Vec (all)
    meaning1 = np.zeros(model.vectors.shape[1])
    for word in tags1:
        if word[2] in model:
            meaning1 += model[word[2]]

    meaning2 = np.zeros(model.vectors.shape[1])
    for word in tags2:
        if word[2] in model:
            meaning2 += model[word[2]]

    diffMeaning = meaning1 - meaning2
    features[6] = np.linalg.norm(diffMeaning)
    features[7] = scipy.spatial.distance.cosine(meaning1, meaning2)

    similarityMatrix = [0] * len(tags1)
    for index1, word1 in enumerate(tags1):
        row = [0]*len(tags2)
        for index2, word2 in enumerate(tags2):
            similarityMax = 0
            if len(word1) > 3 and len(word2) > 3:
                for sense1, sense2 in product(word1[3], word2[3]):
                    sim = wordnet.wup_similarity(sense1, sense2)
                    similarityMax = max(similarityMax, sim)
                similarityMax = 1 - similarityMax
            else:
                similarityMax = 1

            row[index2] = similarityMax
        similarityMatrix[index1] = row
    m = Munkres()
    totalCost = 0
    indices = m.compute(similarityMatrix)
    for row, column in indices:
        totalCost += similarityMatrix[row][column]

    features[8] = totalCost / len(indices)

    return features
Esempio n. 28
0
    def envoiTweets(self):
        print "@----Envoi des tweets--@"
        cursor = conn.cursor()
        lastId = "0"
        query = "SELECT * FROM tweetAnalyser WHERE temps > (now() - interval 20 second - interval 2 hour) and tweetId > " + lastId
        query50 = "SELECT DISTINCT mot, COUNT(tweetId) AS frequency FROM linkKeywordTweet GROUP BY mot ORDER BY frequency DESC LIMIT 10"
        while not thread_stop_event.isSet():
            cursor.execute(query)
            dataMysql = cursor.fetchall()
            cursor.execute(query50)
            dataMysql50 = cursor.fetchall()
            listmotkey = []
            for elt in dataMysql50:
                coooo = (elt[0], elt[1])
                listmotkey.append(coooo)
            liste = []
            for elt in dataMysql:
                texte = elt[1][2:][:len(elt[1]) - 4]
                new = (texte, elt[2], elt[3], json.dumps(elt[4]))  #,elt[5])
                socketio.emit('reponse', {
                    'motsCles': listmotkey,
                    'tweets': [new]
                })
                liste.append(new)
                idt = elt[0]
                if lastId <= str(idt):
                    lastId = str(idt)
                s = elt[1].split()
                #				print idt
                tt = TreeTagger(language='english')
                lis = []
                lis = tt.tag(s)
                nostop = []
                #				print lis
                for k in lis:
                    if k[0] not in stop:
                        if ('NN' in k[1]) or ('NP' in k[1]) or (
                                'JJ' in k[1]) or ('VB' in k[1]) or (
                                    '#' in k[0]) and (len(k[0]) > 3):
                            #						print k[1]
                            #						print k [0]
                            motcle = k[0]
                            if "#" in k[0]:
                                motcle = motcle.replace("#", "")
                            if "." in k[0]:
                                motcle = motcle.replace(".", "")
                            motcle = motcle.lower()
                            lis = []
                            if "-" in motcle:
                                lis = motcle.split("-")
                                if "" in lis:
                                    lis.remove("")
                                motcle = ' '.join(lis)
                            if "_" in motcle:
                                lis = motcle.split("_")
                                if "" in lis:
                                    lis.remove("")
                                motcle = ' '.join(lis)
                            inc = 1
                            for letter in motcle:
                                if not letter in "abcdefghijklmnopqrstuvwxyz ":
                                    inc = 0
                            if (inc != 0) and (len(motcle) > 3):
                                nostop.append(motcle)

                            #print motcle

                for mot in nostop:
                    query1 = """INSERT INTO keyword (mot) VALUES (%s)"""
                    query2 = """INSERT INTO linkKeywordTweet (tweetId,mot) VALUES (%s,%s)"""
                    query3 = "select * from keyword where mot = (%s)"
                    query4 = "select * from linkKeywordTweet  where mot = (%s) and tweetId = (%s)"

                    cur = conn.cursor()
                    cur.execute(query3, (str(mot)))
                    dataMysql3 = cur.fetchall()

                    s = str(mot)
                    if len(s) < 31:

                        if dataMysql3 == ():
                            cur.execute(query1, (str(mot)))
                        #else:
                        #	print ' that shit existe so no insert into keyword'
                        cur.execute(query4, (str(mot), str(idt)))
                        dataMysql4 = cur.fetchall()
                        if dataMysql4 == ():
                            #	print str(mot)
                            #	print str(idt)
                            #print s + '------ add it '
                            cur.execute(query2, (str(idt), str(mot)))
                        #else:
                        #	print ' that shit existe so no insert into linkKeywordTweet'
                    #else :
                    #print s + '------ couldnt add it because of reasons '
                    conn.commit()
                nostop = []
            conn.commit()
Esempio n. 29
0
def tagLang(langs, corpus):
    if "fr" in langs:
        frTagDict = convertTags('fr-treetagger.map')
        frTagger = TreeTagger(encoding='utf-8', language='french')
    if "sl" in langs:
        slTagDict = convertTags('sl-treetagger.map')
        slTagger = TreeTagger(encoding='utf-8', language='slovenian')
    if "de" in langs:
        deTagDict = convertTags('de-tiger.map')
        deTagger = TreeTagger(encoding='utf-8', language='german')
    if "it" in langs:
        itTagDict = convertTags('it-treetagger.map')
        itTagger = TreeTagger(encoding='utf-8', language='italian')
    if "pl" in langs:
        plTagDict = convertTags('pl-treetagger.map')
        plTagger = TreeTagger(encoding='utf-8', language='polish')
    if "sk" in langs:
        skTagDict = convertTags('sk-treetagger.map')
        skTagger = TreeTagger(encoding='utf-8', language='slovak')
    if "es" in langs:
        esTagDict = convertTags('es-treetagger.map')
        esTagger = TreeTagger(encoding='utf-8', language='spanish')
    if "nl" in langs:
        nlTagDict = convertTags('nl-treetagger.map')
        nlTagger = TreeTagger(encoding='utf-8', language='dutch')
    engTagger = TreeTagger(encoding='utf-8', language='english')
    engTagDict = convertTags('en-ptb.map')
    corpus = open(corpus, 'r')
    output = open('tagged.all', 'w')
    errors = open('errors.txt', 'w')
    numLines = 0

    for line in corpus:
        #numLines += 1
        #print numLines
        if line.startswith("<fr>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, frTagDict, frTagger, "fr", output, errors)
        elif line.startswith("<sl>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, slTagDict, slTagger, "sl", output, errors)
        elif line.startswith("<de>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, deTagDict, deTagger, "de", output, errors)
        elif line.startswith("<it>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, itTagDict, itTagger, "it", output, errors)
        elif line.startswith("<pl>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, plTagDict, plTagger, "pl", output, errors)
        elif line.startswith("<sk>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, skTagDict, skTagger, "sk", output, errors)
        elif line.startswith("<es>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, esTagDict, esTagger, "es", output, errors)
        elif line.startswith("<nl>"):
            splitline = line.split(" ")
            notag = " ".join(splitline[1:])
            tagWrite(notag, nlTagDict, nlTagger, "nl", output, errors)
        elif line.startswith("-1") or line[0].isdigit():
            splitline = line.split(",")
            output.write("\t".join(splitline))
        elif line.startswith("!@#$%^&*()"):
            output.write(line)
        else:
            tagWrite(line, engTagDict, engTagger, "en", output, errors)
Esempio n. 30
0
def tags(raw):
    tagger = TreeTagger(language='portuguese')
    return tagger.tag(raw.lower())
class NegationDetector(object):
    """
    Class to detect negations for the following languages:
        * Dutch
        * English
        * Spanish
    """
    
    supported_languages = {'dutch', 'english', 'spanish'}
    
    def __init__(self, language):
        "Initialize NegationDetector with a specific language."
        self.this_dir, self.this_filename = os.path.split(__file__)
        self.language = language
        self._tokenizers = {'dutch': 'tokenizers/punkt/dutch.pickle',
                          'english': '',
                          'spanish': 'tokenizers/punkt/spanish.pickle'}
        self.json_files = {'english': 'english_negations.json'}
        
        # Check if the entered language is supported.
        try:
            assert self.language in self.json_files
        except AssertionError:
            raise NotImplementedError('Unsupported language!')
        
        self.json_path = os.path.join(self.this_dir, 'data', self.json_files[self.language])
        with open(self.json_path) as f:
            # Load the lexicon.
            self.lexicon = {kind: set(words) for kind, words in json.load(f).items()}
        self.tagger = TreeTagger(language=self.language)
        
        if language == 'english':
            # English is the standard in NLTK
            from nltk.tokenize import sent_tokenize
            self.sent_tokenize = sent_tokenize
        else:
            # Other languages have to be loaded using Pickle.
            pickle_path = self.tokenizers[language]
            self.sent_tokenize = nltk.data.load(pickle_path).tokenize
    
    def prefix_check(self, word_form, prefixes):
        "Check whether a word starts with one of several prefixes."
        for pref in prefixes:
            if word_form.startswith(pref):
                return True, pref
        return False, None
    
    def suffix_check(self, word_form, prefixes):
        "Check whether a word starts with one of several prefixes."
        for suff in suffixes:
            if word_form.endswith(suff):
                return True, suff
        return False, None
    
    def negation_status(word, pos, lemma, use_affixes=False):
        """
        Checks whether the word is a negation or not.
        Returns truth value and kind of negation.
        """
        word = word.lower()
        match = False
        kind = None
        if word in self.lexicon["WHOLEWORD"]:
            match = True
            kind = 'wholeword'
        elif lemma in self.lexicon["LEMMA"]:
            match = True
            kind = 'lemma'
        elif use_affixes:
            if pos.lower().startswith('v'):
                # Check verbs.
                # Check for negative prefix.
                prefixed, prefix = self.prefix_check(word, self.lexicon["VERB_STARTSWITH"])
                if prefixed:
                    match = True
                    kind = 'verb-prefix-' + prefix
            elif pos.lower.startswith('n'):
                # Check for negative prefix.
                prefixed, prefix = self.prefix_check(word, self.lexicon["NOUN_STARTSWITH"])
                if prefixed:
                    match = True
                    kind = 'noun-prefix-' + prefix
            elif pos.lower() in {'adj', 'jj'}:
                # Check adjectives.
                # Check for negative prefix.
                prefixed, prefix = self.prefix_check(word, self.lexicon["ADJ_STARTSWITH"])
                if prefixed:
                    match = True
                    kind = 'adj-prefix-' + prefix
                # Check for negative suffix.
                suffixed, suffix = self.suffix_check(word, self.lexicon["ADJ_ENDSWITH"])
                if suffixed:
                    match = True
                    kind = 'adj-suffix-' + suffix
        return match, kind
    
    def check_sentence(self, sentence, use_affixes=False):
        """
        Detect negations in a sentence. use_affixes yields many false positives,
        but might be useful to extend the negations file.
        """
        sentence_data = []
        tagged = self.tagger.tag(sentence)
        for idx, data in enumerate(tagged):
            word, pos, lemma = data
            match, kind = self.negation_status(word, pos, lemma, use_affixes)
            token = Token(idx, word, pos, lemma, match, kind)
            sentence_data.append(token)
        return sentence_data
    
    def check_text(self, text, use_affixes=False):
        """
        Detect negations in a text. use_affixes yields many false positives,
        but might be useful to extend the negations file.
        """
        return [check_sentence(sent, use_affixes) for sent in self.sent_tokenize(text)]
Esempio n. 32
0
class AplicadorPLN(object):
    crefdoc: CoreferenceDocument

    # -----------------------------------V A R I Á V E I S --- G L O B A I S---------------------

    def __init__(self, path_projeto, noticia, legenda, titulo, path, path_dir):
        self.path_projeto = path_projeto
        self.diretorio = path_projeto + path_dir
        self.path_noticia = path_projeto + path
        self.noticia = noticia
        self.noticia_inicial = noticia
        self.legenda = legenda
        self.titulo = titulo
        self.lst_top_substantivos = []
        self.lst_top_entidades_nomeadas = []
        self.total_entidades = 0
        self.tipo_wordNet = ""
        self.lst_EntidadesNomeadas = []
        self.lst_interseccao_entidades = []
        self.lst_top_substantivos_physical = []
        self.lst_top_substantivos_objects = []
        self.lst_diferenca_entidades = []
        self.dict_lematizado = {}
        self.chunker = MWEChunker()

        self.crefdoc = CoreferenceDocument()
        self.snt_tok = []

        PATH_LOCATION = os.path.dirname(os.path.abspath(__file__))
        print(PATH_LOCATION)

        TREE_TAGGER_PATH = PATH_LOCATION + '/TreeTagger'
        print('exportando tree tagger em ', TREE_TAGGER_PATH)
        os.environ["TREETAGGER_HOME"] = TREE_TAGGER_PATH

        self.tree_tagger = TreeTagger(language='english')

    def SomentePalavras_physical(self):
        lst_palavras = []
        for x in range(0, len(self.lst_top_substantivos_physical)):
            lst_palavras.append(self.lst_top_substantivos_physical[x].palavra)
        return lst_palavras

    def file_to_List(self, file_name):
        lista = []
        with open(file_name, 'rt') as f:
            for line in f:
                lista.append(line.replace('\n', ''))
        return lista

    def SomentePalavras_objects(self):
        lst_palavras = []
        for x in range(0, len(self.lst_top_substantivos_objects)):
            lst_palavras.append(self.lst_top_substantivos_objects[x].palavra)
        return lst_palavras

    def read_words(self, arquivo_txt):
        open_file = open(arquivo_txt, 'r')
        words_list = []
        contents = open_file.readlines()
        for i in range(len(contents)):
            words_list.extend(contents[i].split())
        open_file.close()
        return words_list

    def read_words_visual(self, arquivo_txt):
        open_file = open(arquivo_txt, 'r')
        words_list = []
        contents = open_file.readlines()
        for content in contents:
            content = content.replace('\n', '')
            if content not in words_list:
                words_list.append(content)
        open_file.close()
        return words_list

    # Filtra o texto removendo caracteres que atrapalham o TreeTagger e EN.
    def FiltrarTexto(self):
        self.noticia = self.noticia.replace("'s", " ")
        self.noticia = self.noticia.replace("'s", " ")
        self.noticia = self.noticia.replace("//", " ")
        self.noticia = self.noticia.replace("%,", " ")
        self.noticia = self.noticia.replace("%:", " ")
        self.noticia = self.noticia.replace("%?", " ")
        self.noticia = self.noticia.replace("%!", " ")
        self.noticia = self.noticia.replace("%.", " ")
        self.noticia = self.noticia.replace("%", " ")
        self.noticia = self.noticia.replace(":", ". ")
        self.noticia = self.noticia.replace(".", ". ")
        self.noticia = self.noticia.replace(";", " ")
        self.noticia = self.noticia.replace("n't", " not")
        self.noticia = self.noticia.replace("?T", "? T")
        self.noticia = self.noticia.replace("I'm", "I am")
        self.noticia = self.noticia.replace('"', '')
        self.noticia = self.noticia.replace("[", "")
        self.noticia = self.noticia.replace("]", "")
        self.noticia = self.noticia.replace("?", "")
        self.noticia = self.noticia.replace("'", "")
        self.noticia = self.noticia.replace("(", "")
        self.noticia = self.noticia.replace(")", "")
        self.noticia = self.noticia.replace('–', ' ')
        self.noticia = self.noticia.replace("´", "")
        self.noticia = self.noticia.replace("-", " ")
        self.noticia = self.noticia.replace(" , ", " ")
        self.noticia = self.noticia.replace("Translated by TOM GATEHOUSE", " ")

    # -----------------TREE TAGGER e STANFORD NER

    def AplicarStanforNER_legenda(self):
        lst_ner_temp = self.stanfordner.tag(self.legenda.split())
        # Junta entidades nomeadas  da mesma pessoa
        lst_ner = []
        for x in range(0, len(lst_ner_temp)):
            if x < (len(lst_ner_temp) - 1):
                if lst_ner_temp[x][1] == "PERSON":
                    entidade = lst_ner_temp[x][0]
                    if lst_ner_temp[x + 1][1] == "PERSON":
                        entidade += " " + lst_ner_temp[x + 1][0]
                    lst_ner.append(entidade)
        return lst_ner

    def AplicarTreeTagger(self):
        global lst_treetagger
        lst_treetagger = []
        lst_treetagger_temp = self.tree_tagger.tag(self.noticia)
        num_palavras_tagger = len(lst_treetagger_temp)
        # Remove as pontuações do tree tagger gerando uma nova lista
        for x in range(0, num_palavras_tagger):
            if lst_treetagger_temp[x][0] != "." and lst_treetagger_temp[x][0] != "!" and lst_treetagger_temp[x][
                0] != "?" and lst_treetagger_temp[x][0] != ":" and lst_treetagger_temp[x][0] != ";" and \
                    lst_treetagger_temp[x][0] != "," and lst_treetagger_temp[x][0] != "(" and lst_treetagger_temp[x][
                0] != ")" and lst_treetagger_temp[x][0] != '"' and lst_treetagger_temp[x][0] != "'" and \
                    lst_treetagger_temp[x][0] != "´" and lst_treetagger_temp[x][0] != "`":
                lst_treetagger.append(lst_treetagger_temp[x])

    def AplicarChunk(self):
        global lst_treetagger
        if self.chunker.set_list_tt(lst_treetagger):
            lst_treetagger = self.chunker.chunk()

    def ResolveCoreferences(self):
        """

        :return:
        """

        _snt_titulo = self.titulo
        if '.' not in self.titulo:
            _snt_titulo += '.'

        _snt_legenda = self.legenda
        if '.' not in self.legenda and self.legenda != '':
            _snt_legenda += '.'

        sentences = f'{_snt_titulo} {_snt_legenda} {self.noticia}'

        sentences = sentences.replace('"', '')
        # TODO: Resolution with quotes in text

        cnlpw = CoreNLPWrapper()
        coref_dict = cnlpw.coreference_resolution(sentences=sentences,
                                                  comm=True)
        self.crefdoc.load_dict(coref_dict, sentences)
        _tokenizeds = self.crefdoc.get_tkn_snts()

        self.snt_tok = [
            element for element in zip([
                ' '.join([str(token) for token in token_list])
                for token_list in _tokenizeds
            ], _tokenizeds)
        ]

    def get_crefdoc(self):
        return self.crefdoc

    def get_snt_tok(self):
        return self.snt_tok

    def AplicarStanforNER(self):
        lst_ner = self.stanfordner.tag(self.noticia.split())
        return lst_ner

    # ---- Filtra a palavra e devolve se for substantivo

    def FiltrarSubstantivos(self, treetagger_pos):
        tipo_morfo = treetagger_pos[1]
        if "NP" in tipo_morfo or "NPS" in tipo_morfo or "NN" in tipo_morfo or "NNS" in tipo_morfo:
            return 1
        else:
            return -1

    # -----------------------FUNÇÃO MAIS IMPORTANTE DO SISTEMA-------------------

    def ObterEntidadesNomeadas_SubstantivosValidos(self, tipo):  #
        self.tipo_wordNet = tipo
        global lst_substantivosValidos
        lst_substantivosValidos = []
        self.lst_EntidadesNomeadas = []
        # percorre o texto  original e do treetagger e atribui indices para o tree tagger
        global lst_ner
        lst_ner = []
        # lst_ner = self.AplicarStanforNER()
        lst_entidades_nltk = TrazerEntidadesNomeadas(self.path_noticia)
        entidades = []
        nomes_texto = []

        # Filtra as entidades nomeadas removendo duplicidade
        for entidade in lst_entidades_nltk:
            remover = False
            a = entidade.split(" ")
            for x in a:
                if x not in nomes_texto:
                    nomes_texto.append(x)
                else:
                    remover = True
            if not remover:
                entidades.append(entidade)

        for entidade_nomeada in entidades:

            max_ocorrencias = 0
            presente_titulo = 0
            presente_legenda = 0

            for nome in entidade_nomeada.split():
                ocorrencias = self.ContarNumeroEntidadesNomeadas(nome)
                if ocorrencias > max_ocorrencias:
                    max_ocorrencias = ocorrencias

                legenda = self.VerificarPresencaLegenda(nome)
                if legenda != 0:
                    presente_legenda = 1

                titulo = self.VerificarPresencaTitulo(nome)
                if titulo != 0:
                    presente_titulo = 1

            entidade = EntidadeNomeada(entidade_nomeada, max_ocorrencias,
                                       presente_legenda, presente_titulo)
            self.lst_EntidadesNomeadas.append(entidade)

        print("TITULO DA NOTICIA:" + self.titulo)
        texto_lematizado = ''
        palavras_fisicas = []
        if [''] in lst_treetagger:
            lst_treetagger.remove([''])
        for x in range(0, len(lst_treetagger)):
            # Monta o dict de palavras lematizadas
            self.dict_lematizado[lst_treetagger[x]
                                 [2].lower()] = lst_treetagger[x][0]

            word_filtrada = lst_treetagger[x][2]
            tipo_morfo = lst_treetagger[x][1]
            lema = lst_treetagger[x][2]
            texto_lematizado += ' ' + lema
            entidade_nomeada = "O"

            if word_filtrada in lst_entidades_nltk:
                entidade_nomeada = "PERSON"

            p = Palavra(x, word_filtrada, tipo_morfo, lema, entidade_nomeada,
                        "", "", 0, 0, 1, 0, 0, x)

            if entidade_nomeada == "O":
                retorno = self.FiltrarSubstantivos(lst_treetagger[x])
                if retorno == 1:
                    palavra_fisica = self.DescobrirPalavraFisica(
                        word_filtrada, tipo
                    )  # descobre se a palavra é fisica a partir do tipo desejado(
                    # physical_entity,object)
                # se for substantivo,palavra fisica(segundo wordNet), e NÃO for nem localizacao e nem organizacao
                # ->coloca no list
                if retorno == 1 and palavra_fisica == 1 and entidade_nomeada != "ORGANIZATION" and entidade_nomeada != "LOCATION":
                    palavras_fisicas.append(word_filtrada)
                    # verifica se a palavra está na legenda
                    legenda = self.VerificarPresencaLegenda(word_filtrada)
                    p.presente_legenda = legenda
                    # verifica se a palavra está no título
                    titulo = self.VerificarPresencaTitulo(word_filtrada)
                    p.presente_titulo = titulo
                    lst_substantivosValidos.append(p)  # grava no list

        # self.PreencherAnteriorPosterior()  # preenche as palavras anteriores e posteriores

        # ---------------Substantivos--------------

        # self.ContarDocumentos_substantivos()
        # self.ContarNumeroPalavrasCorpus_substantivos()
        print('TEXTO LEMATIZADO:' + texto_lematizado)
        print(palavras_fisicas)
        self.ContarNumeroPalavrasTexto_substantivos()

    # ---------------Entidades Nomeadas--------------
    # self.ContarDocumentos_entidadesNomeadas()
    # self.ContarNumeroPalavrasCorpus_entidadesNomeadas()
    # self.ContarNumeroPalavrasTexto_entidades_nomeadas()

    # -----------------OrganizarTopSubstantivos---------------Funções

    def get_dict_lematizado(self):
        return self.dict_lematizado

    def VerificarPresencaLegenda(self, palavra):

        lst_palavrasLegenda = self.ObterPalavrasLegenda()
        for x in range(0, len(lst_palavrasLegenda)):
            if lst_palavrasLegenda[x] == palavra:
                return 1
        return 0

    def VerificarPresencaTitulo(self, palavra):
        lst_palavrasTitulo = self.ObterPalavrasTitulo()
        for x in range(0, len(lst_palavrasTitulo)):
            if lst_palavrasTitulo[x] == palavra:
                return 1
        return 0

    def ObterPalavrasLegenda(self):
        return self.legenda.split()

    def ObterPalavrasTitulo(self):
        return self.titulo.split()

    def PreencherAnteriorPosterior(self):
        total_palavras = len(self.lst_EntidadesNomeadas)
        global lst_ner

        for x in range(0, total_palavras):

            if x != 0:
                index = self.lst_EntidadesNomeadas[x].indice_treetagger - 1
                try:
                    entidade_nomeada = lst_ner[index][1]
                except:
                    entidade_nomeada = "O"
                if entidade_nomeada == "PERSON":
                    juncao_string1 = self.lst_EntidadesNomeadas[x - 1].palavra + \
                                     "." + self.lst_EntidadesNomeadas[x].palavra
                    juncao_string2 = self.lst_EntidadesNomeadas[x - 1].palavra + \
                                     ". " + self.lst_EntidadesNomeadas[x].palavra
                    if juncao_string1 not in self.noticia and juncao_string2 not in self.noticia:
                        self.lst_EntidadesNomeadas[
                            x].anterior = self.lst_EntidadesNomeadas[x -
                                                                     1].palavra

                    # se não for a ultima palavra do texto, pega a palavra posterior
            if x != total_palavras - 1:
                indexPos = self.lst_EntidadesNomeadas[x].indice_treetagger + 1
                try:
                    entidade_nomeada = lst_ner[indexPos][1]
                except:
                    entidade_nomeada = "O"

                if entidade_nomeada == "PERSON":
                    juncao_string1 = self.lst_EntidadesNomeadas[x].palavra + \
                                     "." + self.lst_EntidadesNomeadas[x + 1].palavra
                    juncao_string2 = self.lst_EntidadesNomeadas[x].palavra + \
                                     ". " + self.lst_EntidadesNomeadas[x + 1].palavra
                    if juncao_string1 not in self.noticia and juncao_string2 not in self.noticia:
                        self.lst_EntidadesNomeadas[
                            x].posterior = self.lst_EntidadesNomeadas[
                                x + 1].palavra

    def ContarNumeroPalavrasTexto_entidades_nomeadas(self):
        total_palavras = len(self.lst_EntidadesNomeadas)
        for x in range(0, total_palavras):
            palavra = self.lst_EntidadesNomeadas[x].palavra
            for y in range(0, total_palavras):
                if self.lst_EntidadesNomeadas[
                        y].palavra == palavra:  # se a palavra for igual a palavra do documento, adiciona +1 no numero de documentos que aparece a palavra
                    self.lst_EntidadesNomeadas[
                        x].ocorrencias = self.lst_EntidadesNomeadas[
                            x].ocorrencias + 1

    def ContarNumeroPalavrasTexto_substantivos(self):
        total_palavras = len(lst_substantivosValidos)
        for x in range(0, total_palavras):
            palavra = lst_substantivosValidos[x].palavra
            for y in range(0, total_palavras):
                if lst_substantivosValidos[
                        y].palavra == palavra:  # se a palavra for igual a palavra do documento, adiciona +1 no numero de documentos que aparece a palavra
                    lst_substantivosValidos[
                        x].ocorrencias = lst_substantivosValidos[
                            x].ocorrencias + 1

    def ContarNumeroPalavrasCorpus_entidadesNomeadas(self):
        total_palavras = len(self.lst_EntidadesNomeadas)
        for x in range(0, total_palavras):
            palavra = self.lst_EntidadesNomeadas[x].palavra
            for documento in lst_todasNoticias:  # para cada documento faça
                for word in documento:  # para cada palavra no documento
                    if word == palavra:  # se a palavra for igual a palavra do documento, adiciona +1 no numero de documentos que aparece a palavra
                        self.lst_EntidadesNomeadas[
                            x].total_palavras_documentos = self.lst_EntidadesNomeadas[
                                x].total_palavras_documentos + 1

    def ContarNumeroPalavrasCorpus_substantivos(self):
        total_palavras = len(lst_substantivosValidos)
        for x in range(0, total_palavras):
            palavra = lst_substantivosValidos[x].palavra
            for documento in lst_todasNoticias:  # para cada documento faça
                for word in documento:  # para cada palavra no documento
                    if word == palavra:  # se a palavra for igual a palavra do documento, adiciona +1 no numero de documentos que aparece a palavra
                        lst_substantivosValidos[
                            x].total_palavras_documentos = lst_substantivosValidos[
                                x].total_palavras_documentos + 1

    def ContarDocumentos_entidadesNomeadas(self):
        total_palavras = len(self.lst_EntidadesNomeadas)
        for x in range(0, total_palavras):
            palavra = self.lst_EntidadesNomeadas[x].palavra
            for documento in lst_todasNoticias:  # para cada documento faça
                for word in documento:  # para cada palavra no documento
                    if word == palavra:  # se a palavra for igual a palavra do documento, adiciona +1 no numero de documentos que aparece a palavra
                        self.lst_EntidadesNomeadas[
                            x].numero_documentos = self.lst_EntidadesNomeadas[
                                x].numero_documentos + 1
                        break  # para o for caso encontre a palavra.

    def ContarDocumentos_substantivos(self):
        total_palavras = len(lst_substantivosValidos)
        for x in range(0, total_palavras):
            palavra = lst_substantivosValidos[x].palavra
            for documento in lst_todasNoticias:  # para cada documento faça
                for word in documento:  # para cada palavra no documento
                    if word == palavra:  # se a palavra for igual a palavra do documento, adiciona +1 no numero de documentos que aparece a palavra
                        lst_substantivosValidos[
                            x].numero_documentos = lst_substantivosValidos[
                                x].numero_documentos + 1
                        break  # para o for caso encontre a palavra.

    def ContarNumeroEntidadesNomeadas(self, entidade):
        ocorrencias = 0
        for palavra in lst_treetagger:
            if entidade == palavra[0]:
                ocorrencias += 1
        return ocorrencias

    # ----------------Remover palavras duplicadas e para acoplar entidades nomeadas umas com as outras

    def RemoverPalavras_EntidadesNomeadas(self):
        total_palavras = len(self.lst_EntidadesNomeadas)
        lst_palavras_excluidas = []
        for x in range(0, total_palavras):

            entidade_nomeada = self.lst_EntidadesNomeadas[x].entidade_nomeada
            posterior = self.lst_EntidadesNomeadas[x].posterior
            if entidade_nomeada == "PERSON":
                if posterior != "":  # se posterior não for vazio
                    # procura a ocorrencia da palavra posterior no list e acopla as informações
                    for i in range(0, total_palavras):
                        palavra = self.lst_EntidadesNomeadas[i].palavra

                        if palavra == posterior:  # se encontrar a palavra, acopla as informações

                            self.lst_EntidadesNomeadas[
                                x].palavra_completa = self.lst_EntidadesNomeadas[
                                    x].palavra_completa + " " + palavra  # concatena a palavra
                            self.lst_EntidadesNomeadas[
                                x].segundo_nome = palavra
                            # adiciona essa palavra para excluir
                            lst_palavras_excluidas.append(palavra)
                            # se as ocorrencias forem maiores
                            if self.lst_EntidadesNomeadas[
                                    i].ocorrencias > self.lst_EntidadesNomeadas[
                                        x].ocorrencias:
                                self.lst_EntidadesNomeadas[
                                    x].ocorrencias = self.lst_EntidadesNomeadas[
                                        i].ocorrencias

                            # se o numero de documentos forem maiores
                            if self.lst_EntidadesNomeadas[
                                    i].numero_documentos > self.lst_EntidadesNomeadas[
                                        x].numero_documentos:
                                self.lst_EntidadesNomeadas[
                                    x].numero_documentos = self.lst_EntidadesNomeadas[
                                        i].numero_documentos

                            # se o total de palavras documentos forem maiores
                            if self.lst_EntidadesNomeadas[
                                    i].total_palavras_documentos > self.lst_EntidadesNomeadas[
                                        x].total_palavras_documentos:
                                self.lst_EntidadesNomeadas[
                                    x].total_palavras_documentos = self.lst_EntidadesNomeadas[
                                        i].total_palavras_documentos

                            # se estiver na legenda
                            if self.lst_EntidadesNomeadas[
                                    i].presente_legenda == 1:
                                self.lst_EntidadesNomeadas[
                                    x].presente_legenda = 1
                            # se estiver no titulo
                            if self.lst_EntidadesNomeadas[
                                    i].presente_titulo == 1:
                                self.lst_EntidadesNomeadas[
                                    x].presente_titulo = 1
                            # pega um terceiro nome
                            posterior_pos = self.lst_EntidadesNomeadas[
                                i].posterior
                            if posterior_pos != "":  # se posterior não for vazio
                                # procura a ocorrencia da palavra posterior no list e acopla as informações
                                for j in range(0, total_palavras):
                                    palavra = self.lst_EntidadesNomeadas[
                                        j].palavra

                                    if palavra == posterior_pos:  # se encontrar a palavra, acopla as informações

                                        self.lst_EntidadesNomeadas[
                                            x].palavra_completa = self.lst_EntidadesNomeadas[
                                                x].palavra_completa + " " + palavra  # concatena a palavra
                                        self.lst_EntidadesNomeadas[
                                            x].terceiro_nome = palavra
                                        # adiciona essa palavra para excluir
                                        lst_palavras_excluidas.append(palavra)
                                        # se as ocorrencias forem maiores
                                        if self.lst_EntidadesNomeadas[
                                                j].ocorrencias > self.lst_EntidadesNomeadas[
                                                    x].ocorrencias:
                                            self.lst_EntidadesNomeadas[
                                                x].ocorrencias = self.lst_EntidadesNomeadas[
                                                    j].ocorrencias

                                        # se o numero de documentos forem maiores
                                        if self.lst_EntidadesNomeadas[
                                                j].numero_documentos > self.lst_EntidadesNomeadas[
                                                    x].numero_documentos:
                                            self.lst_EntidadesNomeadas[x].numero_documentos = \
                                                self.lst_EntidadesNomeadas[
                                                    j].numero_documentos

                                        # se o total de palavras documentos forem maiores
                                        if self.lst_EntidadesNomeadas[j].total_palavras_documentos > \
                                                self.lst_EntidadesNomeadas[x].total_palavras_documentos:
                                            self.lst_EntidadesNomeadas[x].total_palavras_documentos = \
                                                self.lst_EntidadesNomeadas[
                                                    j].total_palavras_documentos

                                        # se estiver na legenda
                                        if self.lst_EntidadesNomeadas[
                                                j].presente_legenda == 1:
                                            self.lst_EntidadesNomeadas[
                                                j].presente_legenda = 1
                                        # se estiver no titulo
                                        if self.lst_EntidadesNomeadas[
                                                j].presente_titulo == 1:
                                            self.lst_EntidadesNomeadas[
                                                x].presente_titulo = 1
        # agora exclui do list as palavras que são segundo e terceiros nomes
        # para cada palavra, excluir todas ocorrencias
        for w in range(0, len(lst_palavras_excluidas)):
            existe_palavra = 1
            while existe_palavra == 1:  # se for == 0 sai do loop e vai para a proxima palavra
                total_palavras = len(self.lst_EntidadesNomeadas)
                palavra = lst_palavras_excluidas[w]
                for j in range(0, total_palavras
                               ):  # varre o list e exclui a palavra do list
                    existe_palavra = 0  # nao existe a palavra, a menos que a encontre
                    # se encontrar a palavra, exclui do list
                    if palavra == self.lst_EntidadesNomeadas[j].palavra:
                        self.lst_EntidadesNomeadas.remove(
                            self.lst_EntidadesNomeadas[j])
                        existe_palavra = 1  # a palavra foi encontrada
                        break  # sai do loop e vai testar a condicao while

    def RemoverPalavrasDuplicadas_entidadesNomeadas(self):

        continuar = 0
        x = 0
        while continuar == 0:
            palavra = self.lst_EntidadesNomeadas[x].palavra

            finalizou = 0
            while finalizou == 0:
                finalizou = 1
                total_palavras = len(self.lst_EntidadesNomeadas)
                for y in range(0, total_palavras):
                    if y != x:  # evita apagar a palavra a ser pesquisada
                        if palavra == self.lst_EntidadesNomeadas[y].palavra:
                            finalizou = 0
                            # verifica se o segundo nome esta vazio.
                            if self.lst_EntidadesNomeadas[x].posterior == "":
                                self.lst_EntidadesNomeadas[
                                    x].posterior = self.lst_EntidadesNomeadas[
                                        y].posterior  # tenta colocar o segundo nome da ocorrencia a ser apagada

                            self.lst_EntidadesNomeadas.remove(
                                self.lst_EntidadesNomeadas[y])
                            break

            x = x + 1
            total_palavras = len(self.lst_EntidadesNomeadas)
            if x == total_palavras:
                break  # sai do laço

    def RemoverPalavrasDuplicadas_substantivos(self):

        continuar = 0
        x = 0
        while continuar == 0:
            palavra = lst_substantivosValidos[x].palavra

            finalizou = 0
            while finalizou == 0:
                finalizou = 1
                total_palavras = len(lst_substantivosValidos)
                for y in range(0, total_palavras):
                    if y != x:  # evita apagar a palavra a ser pesquisada
                        if palavra == lst_substantivosValidos[y].palavra:
                            finalizou = 0
                            lst_substantivosValidos.remove(
                                lst_substantivosValidos[y])
                            break

            x = x + 1
            total_palavras = len(lst_substantivosValidos)
            if x == total_palavras:
                break  # sai do laço

    # ---------------Organizar as palavras em ordem de importância
    def OrganizarTopSubstantivos(self):
        global lst_treetagger
        # organiza as cinco palavras mais importantes do texto
        self.lst_top_substantivos = []
        lst_legenda_titulo = []
        lst_legenda = []
        lst_titulo = []
        lst_frequencia_texto = []
        lst_palavra = []

        self.RemoverPalavrasDuplicadas_substantivos()
        # self.total_entidades = self.ContarNumeroEntidadesNomeadas()
        # print("TOTAL DE ENTIDADES________________________= "+str(self.total_entidades))
        total_palavras = len(lst_substantivosValidos)

        for x in range(0, total_palavras):  # para cada palavra

            if lst_substantivosValidos[x].palavra in lst_palavra:
                continue

            # ----------------------- Verifica se está em titulo,legenda,etc e Coloca nos lists
            # pega somente palavras com 2 ou mais ocorrencias no texto
            if lst_substantivosValidos[x].ocorrencias >= 1:
                if lst_substantivosValidos[
                        x].presente_legenda == 1 and lst_substantivosValidos[
                            x].presente_titulo:
                    lst_legenda_titulo.append(lst_substantivosValidos[x])
                # lst_palavra.append(lst_substantivosValidos[x].palavra)

                elif lst_substantivosValidos[x].presente_legenda == 1:
                    lst_legenda.append(lst_substantivosValidos[x])
                # lst_palavra.append(lst_substantivosValidos[x].palavra)

                elif lst_substantivosValidos[x].presente_titulo == 1:
                    lst_titulo.append(lst_substantivosValidos[x])
                #  lst_palavra.append(lst_substantivosValidos[x].palavra)

                elif lst_substantivosValidos[x].ocorrencias >= 1:
                    lst_frequencia_texto.append(lst_substantivosValidos[x])
                #  lst_palavra.append(lst_substantivosValidos[x].palavra)

        contador = 0
        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_legenda_titulo)
        count = 0
        while count < max_value and tamanho_lista > 0:  # ESVAZIA A LISTA
            # pega o tamanho da lista atual
            tamanho_lista = len(lst_legenda_titulo)
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_legenda_titulo[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_legenda_titulo[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                # coloca no top 5
                lst_palavra.append(lst_legenda_titulo[indice_palavra].palavra)
                # remove da lista a palavra já utilizada
                lst_legenda_titulo.remove(lst_legenda_titulo[indice_palavra])
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1
        # ---------------------------------------------- WHile para presente na legenda
        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_legenda)
        count = 0
        while count < max_value and tamanho_lista > 0:
            tamanho_lista = len(lst_legenda)  # pega o tamanho da lista atual
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_legenda[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_legenda[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                # coloca no top 5
                lst_palavra.append(lst_legenda[indice_palavra].palavra)
                # remove da lista a palavra já utilizada
                lst_legenda.remove(lst_legenda[indice_palavra])
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1

        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_titulo)
        count = 0
        while count < max_value and tamanho_lista > 0:
            tamanho_lista = len(lst_titulo)  # pega o tamanho da lista atual
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_titulo[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_titulo[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                # coloca no top 5
                lst_palavra.append(lst_titulo[indice_palavra].palavra)
                # remove da lista a palavra já utilizada
                lst_titulo.remove(lst_titulo[indice_palavra])
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1

        # -------------------------while para ocorrencias---------------------
        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_frequencia_texto)
        count = 0
        while count < max_value and tamanho_lista > 0:
            # pega o tamanho da lista atual
            tamanho_lista = len(lst_frequencia_texto)
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_frequencia_texto[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_frequencia_texto[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                # coloca no top 5
                lst_palavra.append(
                    lst_frequencia_texto[indice_palavra].palavra)
                lst_frequencia_texto.remove(
                    lst_frequencia_texto[indice_palavra]
                )  # remove da lista a palavra já utilizada
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1

        # ---ADICIONA PALAVRAS DO TITULO SE NAO EXISTIREM NO LST_PALAVRA
        print(self.titulo)
        lst_treetagger_titulo = self.tree_tagger.tag(self.titulo)
        if [''] in lst_treetagger_titulo:
            lst_treetagger_titulo.remove([''])
        lst_treetagger += lst_treetagger_titulo
        for x in range(0, len(lst_treetagger_titulo)):

            word_filtrada = lst_treetagger_titulo[x][2]
            lema = lst_treetagger_titulo[x][2]

            print(lema)
            retorno = self.FiltrarSubstantivos(lst_treetagger_titulo[x])
            if retorno == 1:
                palavra_fisica = self.DescobrirPalavraFisica(
                    word_filtrada, self.tipo_wordNet
                )  # descobre se a palavra é fisica a partir do tipo desejado(physical_entity,object)
            # se for substantivo,palavra fisica(segundo wordNet), e NÃO for nem localizacao e nem organizacao ->coloca no list
            if retorno == 1 and palavra_fisica == 1:
                if word_filtrada not in lst_palavra:
                    lst_palavra.append(word_filtrada)

        # ---ADICIONA PALAVRAS DA LEGENDA SE NAO EXISTIREM NO LST_PALAVRA
        lst_treetagger_legenda = self.tree_tagger.tag(self.legenda)
        if [''] in lst_treetagger_legenda:
            lst_treetagger_legenda.remove([''])
        lst_treetagger += lst_treetagger_legenda
        if len(lst_treetagger_legenda) < 1:

            for x in range(0, len(lst_treetagger_legenda)):

                word_filtrada = lst_treetagger_legenda[x][2]
                retorno = self.FiltrarSubstantivos(lst_treetagger_legenda[x])
                if retorno == 1:
                    palavra_fisica = self.DescobrirPalavraFisica(
                        word_filtrada, self.tipo_wordNet
                    )  # descobre se a palavra é fisica a partir do tipo desejado(physical_entity,object)
                # se for substantivo,palavra fisica(segundo wordNet), e NÃO for nem localizacao e nem organizacao ->coloca no list
                if retorno == 1 and palavra_fisica == 1:
                    if word_filtrada not in lst_palavra:
                        lst_palavra.append(word_filtrada)

        if self.tipo_wordNet == "physical_entity.n.01":
            self.lst_top_substantivos_physical = lst_palavra
        elif self.tipo_wordNet == "object.n.01":
            self.lst_top_substantivos_objects = lst_palavra

    def InterseccaoListasSubstantivos(self):
        lst_palavras_fisicas = []
        lst_palavras_objetos = []
        for pysical in self.lst_top_substantivos_physical:
            lst_palavras_fisicas.append(pysical)
        for object in self.lst_top_substantivos_objects:
            lst_palavras_objetos.append(object)
        lst_interseccao = [
            val for val in lst_palavras_fisicas if val in lst_palavras_objetos
        ]
        self.lst_interseccao_entidades = lst_interseccao  # coloca na variavel global

    def DiferencaListasSubstantivos(self):
        lst_palavras_fisicas = []
        lst_palavras_objetos = []
        for pysical in self.lst_top_substantivos_physical:
            lst_palavras_fisicas.append(pysical)
        for objects in self.lst_top_substantivos_objects:
            lst_palavras_objetos.append(pysical)
        lst_diferencas_fisicas = [
            val for val in lst_palavras_fisicas
            if val not in lst_palavras_objetos
        ]
        lst_diferencas_objects = [
            val for val in lst_palavras_objetos
            if val not in lst_palavras_fisicas
        ]
        self.lst_diferenca_entidades = list(set().union(
            lst_diferencas_fisicas,
            lst_diferencas_objects))  # coloca na variavel global

    def OrganizarTopEntidadesNomeadas(self):
        # organiza as cinco palavras mais importantes do texto

        lst_legenda_titulo = []
        lst_legenda = []
        lst_titulo = []
        lst_frequencia_texto = []
        lst_palavra = []

        total_palavras = len(self.lst_EntidadesNomeadas)

        for x in range(0, total_palavras):  # para cada palavra
            # ----------------------- Verifica se está em titulo,legenda,etc e Coloca nos lists
            if self.lst_EntidadesNomeadas[
                    x].presente_legenda == 1 and self.lst_EntidadesNomeadas[
                        x].presente_titulo == 1:
                lst_legenda_titulo.append(self.lst_EntidadesNomeadas[x])
                lst_palavra.append(self.lst_EntidadesNomeadas[x].palavra)
            elif self.lst_EntidadesNomeadas[x].presente_legenda == 1:
                lst_legenda.append(self.lst_EntidadesNomeadas[x])
                lst_palavra.append(self.lst_EntidadesNomeadas[x].palavra)
            elif self.lst_EntidadesNomeadas[x].presente_titulo == 1:
                lst_titulo.append(self.lst_EntidadesNomeadas[x])
                lst_palavra.append(self.lst_EntidadesNomeadas[x].palavra)
            else:
                if self.lst_EntidadesNomeadas[x].ocorrencias > 2:
                    lst_frequencia_texto.append(self.lst_EntidadesNomeadas[x])
                    lst_palavra.append(self.lst_EntidadesNomeadas[x].palavra)

        # ---------------------Seleciona as palavras mais classificadas
        contador = 0
        count = 0

        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_legenda_titulo)
        while count < max_value and tamanho_lista > 0:  # ESVAZIA A LISTA
            # pega o tamanho da lista atual
            tamanho_lista = len(lst_legenda_titulo)
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_legenda_titulo[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_legenda_titulo[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                self.lst_top_entidades_nomeadas.append(
                    lst_legenda_titulo[indice_palavra])  # coloca no top 5
                # remove da lista a palavra já utilizada
                lst_legenda_titulo.remove(lst_legenda_titulo[indice_palavra])
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1
            # ---------------------------------------------- WHile para presente na legenda
        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_legenda)
        count = 0
        while count < max_value and tamanho_lista > 0:
            tamanho_lista = len(lst_legenda)  # pega o tamanho da lista atual
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_legenda[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_legenda[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                self.lst_top_entidades_nomeadas.append(
                    lst_legenda[indice_palavra])  # coloca no top 5
                # remove da lista a palavra já utilizada
                lst_legenda.remove(lst_legenda[indice_palavra])
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1
        # while para ocorrencias
        tamanho_lista = 1  # inicia padrão para usar o while
        max_value = len(lst_frequencia_texto)
        count = 0
        while count < max_value and tamanho_lista > 0:
            # pega o tamanho da lista atual
            tamanho_lista = len(lst_frequencia_texto)
            maior_frequencia = -1  # variavel
            indice_palavra = -1  # variavel
            for x in range(0,
                           tamanho_lista):  # varre a lista de legenda titulo
                # obtem a maior frequencia e seu indice
                if lst_frequencia_texto[x].ocorrencias > maior_frequencia:
                    maior_frequencia = lst_frequencia_texto[x].ocorrencias
                    indice_palavra = x
            if tamanho_lista > 0:
                self.lst_top_entidades_nomeadas.append(
                    lst_frequencia_texto[indice_palavra])  # coloca no top 5
                # remove da lista a palavra já utilizada
                lst_frequencia_texto.remove(
                    lst_frequencia_texto[indice_palavra])
                count = count + 1  # incrementa o contador do top 5
                tamanho_lista = tamanho_lista - 1
                contador = contador + 1

    def DescobrirPalavraFisica(self, palavra, tipo):

        lst = wn.synsets(palavra, pos=wn.NOUN)
        hyper = lambda s: s.hypernyms()
        for j in range(0, len(lst)):
            synset = str(lst[j])
            synset = synset.replace("Synset('", "")
            synset = synset.replace("')", "")
            # print(synset + " ----" + wn.synset(synset).definition())
            word = wn.synset(synset)
            lista_hierarquia = list(word.closure(hyper))
            for w in range(0, len(lista_hierarquia)):
                synset = str(lista_hierarquia[w])
                synset = synset.replace("Synset('", "")
                synset = synset.replace("')", "")
                # print("("+palavra+")"+synset)
                if synset == "location.n.01":
                    return 0
                if tipo == "physical_entity.n.01":  # busca somente esse tipo
                    if synset == "physical_entity.n.01":
                        return 1
                elif tipo == "object.n.01":  # busca somente esse tipo
                    if synset == "object.n.01":
                        return 1

        return 0

    def entidades_legenda(self):
        """ Retorna as entidades nomeadas presentes na legenda da notícia"""
        lst_entidades = trazer_entidades_nomeadas_v(self.legenda)
        return lst_entidades

    def get_list_top_entidades_nomeadas(self):

        return self.lst_top_entidades_nomeadas

    def delete_blank_words(self):
        global lst_treetagger
        if [''] in lst_treetagger:
            lst_treetagger.remove([''])
Esempio n. 33
0
 def test_language(language, phrase):
     dirname, filename = os.path.split(os.path.abspath(__file__))
     tt = TreeTagger(language=language,
                     path_to_home=os.path.join(dirname, 'treetagger', 'cmd'))
     return tt.tag(phrase)
Esempio n. 34
0
def normalize(sentence_to_normalize):
    print_coloured_bold('Sentence to stem:',"green")
    print(sentence_to_normalize + '\n')

    #removing m-dash
    sentence_to_normalize = sentence_to_normalize.replace("–"," ").lower()
    sentence_to_normalize = re.sub("-{2,}","",sentence_to_normalize)

    #removing contract forms
    if("'t" in sentence_to_normalize):
        sentence_to_normalize = sentence_to_normalize.replace("'t","")

    #removing specifications inside parenthesis
    start = sentence_to_normalize.find( '(' )
    end = sentence_to_normalize.find( ')' )
    if start != -1 and end != -1:
      sentence_to_normalize = sentence_to_normalize.replace(sentence_to_normalize[start:end+1],"")

    #tokenization
    word_tokens = word_tokenize(sentence_to_normalize)

    #punctuation removal
    word_tokens_filtered = [w for w in word_tokens if not w in punctuation and not w=="'s"]

    #skip if punctuation within words (except -./) or split if / within word
    word_tokens_noslash = list()
    for w in word_tokens_filtered:
        if any(char in punctuation.replace("-","").replace(".","").replace("/","") for char in w):
            return False
        if "/" in w:
            words = w.split("/")
            for split in words:
                if not split == "":
                    word_tokens_noslash.append(split)
        else:
            word_tokens_noslash.append(w)

    #leave acronyms and split others in case of .
    word_tokens_dot = list()
    regex = re.compile('(?:[a-z]\.){2,}')
    for w in word_tokens_noslash:
        if(w+"." in sentence_to_normalize and regex.match(w+".")):
            word_tokens_dot.append(w)
        elif("." in w):
            words = w.split(".")
            for split in words:
                if not split == "":
                    word_tokens_dot.append(split)
        else:
            word_tokens_dot.append(w)

    #stopwords removal (done before stemming, less words to stem)
    stop_words = set(stopwords.words('english'))
    no_stopwords_sentence = [w for w in word_tokens_dot if not w in stop_words]

    #digits removal
    sentence_words_nodigits = [w for w in no_stopwords_sentence if not w.isdigit()]

    #roman numerals removal
    regex = re.compile('^(?=[MDCLXVI])M*D?C{0,4}L?X{0,4}V?I{0,4}$')
    no_roman_numerals_sentence = [w for w in sentence_words_nodigits if not regex.match(w)]

    #one letter words removal
    sentence_words_nosingleletters = [w for w in no_roman_numerals_sentence if not len(w)<2]
    #print('No one letter words:')

    #stemming
    stemmed_sentence = ""
    stemmer = TreeTagger(path_to_treetagger='/home/biar/Desktop/ProgettoWIR/treetagger')
    for word in sentence_words_nosingleletters:
        stem = stemmer.tag(word)
        if not(stem[0][1] == "CRD"):
            if not stem[0][2] == '<unknown>':
                if '|' in stem[0][2]:
                    first_word = ((stem[0][2]).split('|'))[0]
                    stem[0][2] = first_word
                    if(len(first_word)>1):
                        stemmed_sentence += (correct_stemming(stem).lower() + " ")
                else:
                    if(len((stem[0][2]).lower())>1):
                        stemmed_sentence += (correct_stemming(stem).lower() + " ")
            else:
                stemmed_sentence += ((stem[0][0]).lower() + " ")

    print_coloured_bold('Stemmed sentence:',"yellow")
    print(stemmed_sentence.strip())
    print('\n')
    return stemmed_sentence.strip()