Как вы считаете отрицательное или положительное слово перед конкретным словом - анализ настроений в Python? - PullRequest
0 голосов
/ 19 февраля 2019

Я пытаюсь подсчитать, сколько раз отрицательное слово из списка появляется перед конкретным словом.Например, «Это ужасный ноутбук».Указанное слово является «ноутбуком», я хочу, чтобы вывод имел «Страшный 1» в Python.

def run(path):
    negWords={} #dictionary to return the count
    #load the negative lexicon
    negLex=loadLexicon('negative-words.txt')
    fin=open(path)

    for line in fin: #for every line in the file (1 review per line)
        line=line.lower().strip().split(' ')
        review_set=set() #Adding all the words in the review to a set

        for word in line: #Check if the word is present in the line
            review_set.add(word)  #As it is a set, only adds one time

        for word in review_set:
            if word in negLex:
                if word in negWords:
                    negWords[word]=negWords[word]+1
                else:
                    negWords[word] = 1

    fin.close()
    return negWords

if __name__ == "__main__": 
    print(run('textfile'))

Ответы [ 2 ]

0 голосов
/ 20 февраля 2019

Это должно делать то, что вы ищете, оно использует set & пересечение, чтобы избежать зацикливания.Шаги -

  1. получить отрицательные слова в строке
  2. проверить местоположение каждого слова
  3. , если после этого места записано слово «ноутбук», запишите его

Обратите внимание, что это будет идентифицировать только первое вхождение отрицательного слова в строке, поэтому «ужасный ужасный ноутбук» не будет совпадением.

from collections import defaultdict

def run(path):

    negWords=defaultdict(int)  # A defaultdict(int) will start at 0, can just add.

    #load the negative lexicon
    negLex=loadLexicon('negative-words.txt')
    # ?? Is the above a list or a set, if it's a list convert to set
    negLex = set(negLex)

    fin=open(path)

    for line in fin: #for every line in the file (1 review per line)
        line=line.lower().strip().split(' ')

        # Can just pass a list to set to make a set of it's items.
        review_set = set(line)

        # Compare the review set against the neglex set. We want words that are in
        # *both* sets, so we can use intersection.
        neg_words_used = review_set & negLex

        # Is the bad word followed by the word laptop?            
        for word in neg_words_used:
            # Find the word in the line list
            ix = line.index(word)
            if ix > len(line) - 2:
                # Can't have laptop after it, it's the last word.
                continue

            # The word after this index in the line is laptop.
            if line[ix+1] == 'laptop':
                negWords[word] += 1

    fin.close()
    return negWords

Если выЗаинтересованы только в словах, предшествующих слову «ноутбук», гораздо более разумным подходом было бы найти слово «ноутбук», а затем проверить слово перед этим, чтобы увидеть, является ли оно отрицательным словом.В следующем примере это делается.

  1. найти ноутбук в текущей строке
  2. , если ноутбук не в строке или это первое слово, пропустить строку
  3. получите слово перед ноутбуком, проверьте на наличие отрицательных слов
  4. , если у вас есть совпадение, добавьте его к нашему результату

Это позволяет избежать поиска слов, не относящихся к ноутбукам.

from collections import defaultdict

def run(path):

    negWords=defaultdict(int)  # A defaultdict(int) will start at 0, can just add.

    #load the negative lexicon
    negLex=loadLexicon('negative-words.txt')
    # ?? Is the above a list or a set, if it's a list convert to set
    negLex = set(negLex)

    fin=open(path)

    for line in fin: #for every line in the file (1 review per line)
        line=line.lower().strip().split(' ')

        try:
            ix = line.index('laptop')
        except ValueError:
            # If we dont' find laptop, continue to next line.
            continue

        if ix == 0:
            # Laptop is the first word of the line, can't check prior word.
            continue


        previous_word = line[ix-1]

        if previous_word in negLex:
            # Negative word before the current one.
            negWords[previous_word] += 1

    fin.close()
    return negWords
0 голосов
/ 20 февраля 2019

Похоже, что вы хотите проверить функцию по последовательным словам, вот один из способов сделать это, condition будет проверяться по всем последовательным словам.

text = 'Do you like bananas? Not only do I like bananas, I love bananas!'
trigger_words = {'bananas'}
positive_words = {'like', 'love'}

def condition(w):
    return w[0] in positive_words and w[1] in trigger_words

for c in '.,?!':
    text = text.replace(c, '')

words = text.lower().split()

matches = filter(condition, zip(words, words[1:]))
n_positives = 0
for w1, w2 in matches:
    print(f'{w1.upper()} {w2} => That\'s positive !')
    n_positives += 1
print(f'This text had a score of {n_positives}')

Вывод:

LIKE bananas => That's positive !
LIKE bananas => That's positive !
LOVE bananas => That's positive !
3

Бонус:

  1. Вы можете искать 3 слова подряд, просто изменив zip(w, w[1:]) на zip(w, w[1:], w[2:]) с условием, которое проверяет 3 слова.

  2. Вы можете получить счетчик словаря, выполнив это:

from collections import Counter
counter = Counter((i[0] for i in matches)) # counter = {'like': 2, 'love': 1}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...