Вероятность каждого слова в предложении - PullRequest
0 голосов
/ 15 сентября 2018

У меня есть набор текста, где мне нужно найти вероятность каждого письма в текстах, исключая знаки препинания и цифры.Я подсчитал количество каждой буквы и сформировал его в словарь:

import re
def tokenize(string):
    return re.compile('\w+').findall(string)

from collections import Counter
def word_freq(string): 
    text = tokenize(string.lower())
    str1 = ''.join(str(e) for e in text)
return dict(Counter(str1))

Но я хочу найти вероятность каждой буквы.Кто-нибудь может подсказать, как обновить значения в словаре в одиночку?

1 Ответ

0 голосов
/ 15 сентября 2018

Начиная со своего, вы можете считать слова или буквы.Верните их как диктовку.Их суммируют, сколько всего и сколько такого рода произошло & print:

import re
def tokenize(string):
    return re.compile('\w+').findall(string)

from collections import Counter

def word_freq(string): 
    text = tokenize(string.lower())
    c = Counter(text)           # count the words
    d = Counter(''.join(text))  # count all letters
    return (dict(c),dict(d))    # return a tuple of counted words and letters

data = "This is a text, it contains  dupes and more dupes and dupes of dupes and lkkk."

words, letters = word_freq(data) # count and get dicts with counts

sumWords = sum(words.values())       # sum total words
sumLetters = sum(letters.values())   # sum total letters

# calc / print probability of word
for w in words:
    print("Probability of '{}': {}".format(w,words[w]/sumWords))

# calc / print probability of letter
for l in letters:
    print("Probability of '{}': {}".format(l,letters[l]/sumLetters))

Чтобы изменить ваш диктат на вероятности, просто замените значения диктов на вычисленную вероятность:

# update the counts to propabilities:
for w in words: 
    words[w] = words[w]/sumWords

print ( words) 

Вывод:

# words
Probability of 'this': 0.0625
Probability of 'is': 0.0625
Probability of 'a': 0.0625
Probability of 'text': 0.0625
Probability of 'it': 0.0625
Probability of 'contains': 0.0625
Probability of 'dupes': 0.25
Probability of 'and': 0.1875
Probability of 'more': 0.0625
Probability of 'of': 0.0625
Probability of 'lkkk': 0.0625

# letters
Probability of 't': 0.08333333333333333
Probability of 'h': 0.016666666666666666
Probability of 'i': 0.06666666666666667
# [....] snipped some for brevity
Probability of 'f': 0.016666666666666666
Probability of 'l': 0.016666666666666666
Probability of 'k': 0.05

После повторного вычисления значений words:

{'this': 0.0625, 'is': 0.0625, 'a': 0.0625, 'text': 0.0625, 'it': 0.0625,
 'contains': 0.0625, 'dupes': 0.25, 'and': 0.1875, 'more': 0.0625, 
 'of': 0.0625, 'lkkk': 0.0625}
...