Определение функции для определенных значений одного параметра - PullRequest
0 голосов
/ 06 февраля 2020

Скажем, я хочу определить функцию как

def log_odds_ratio(counts, word, polarity)

, в которой полярность либо положительная, либо отрицательная, оба являются словарями. Моя функция будет состоять из разных формул для каждого случая, либо pos, либо neg. Как я могу продолжать определять свою функцию? Формулы для log_odds_ratio (count, word, pos) и log_odds_ratio (count, word, neg) различны.

edit:

import math

def log_odds_ratio(counts, word, polarity):

This function returns the log odds ratio of a term (see previous cell)

Parameters:
counts (dict): the dictionaries 'pos' and 'neg' which count word occurances
word (str): the word you want to get the probability for
polarity (str): wither 'pos' or 'neg'

Returns:
log_odds_ratio (float): log( prob(word|plarity) / P(word|opposity_polarity) )

"""
# Your code goes here
wordsInPolarity = list(counts[polarity].keys()) #Build a list of words
sumCounts = 0


for word in wordsInPolarity:
    if counts[polarity]='pos':
        log_odds_ratio =math.log(get_word_prob(counts, word, 'pos')/get_word_prob(counts, word, 'neg'))
    if word in counts['neg']:
        log_odds_ratio  =math.log(get_word_prob(counts, word, 'neg')/get_word_prob(counts, word, 'pos'))      
return log_odds_ratio 


Do not change
print(log_odds_ratio(counts, "great", "pos")) # should print 1.2755975445193852
print(log_odds_ratio(counts, "the", "neg")) #  should print -0.09155418404114618
print(log_odds_ratio(counts, "wug", "neg")) # should print a very large number

1 Ответ

1 голос
/ 06 февраля 2020

Как отметили @Prune и @Michael Butscher, лучше всего предоставить минимальный воспроизводимый пример вместе с вашим вопросом. Другими словами, покажите людям, какие попытки вы предприняли для решения проблемы и почему, по вашему мнению, вы потерпели неудачу. Тем не менее, вот что поможет вам начать.

Используйте оператор if.

def log_odds_ratio(counts, word, polarity):
    if polarity: # polarity is positive
        return log_odds_ratio_pos(counts, words)
    else: # polarity is negative
        return log_odds_ratio_neg(counts, words)

Затем определите функции для каждого случая.

def log_odds_ratio_pos(counts ,words): # formula when polarity is positive
    pass # code goes here

def log_odds_ratio_neg(counts ,words): # formula when polarity is negative
    pass # code goes here

Конечно, вы можете просто реализовать это в одной функции, но это не повредит разбить функции на части для лучшего удобочитаемость и более простая отладка.

РЕДАКТИРОВАТЬ

Вы можете обрабатывать все в одной функции с минимальными изменениями.

def log_odds_ratio(counts, word, polarity):
    if polarity: # polarity is positive
        pass # formula goes here
    else: # polarity is negative
        pass # formula goes here
...