在字节对编码算法中,有一个替换步骤,它将由空格分隔的字符串更改为bigrams。 即,给出一个str元组列表: 和一个字符串元组:( ('i', 's') 如何处理列表以便迭代所有元组键并用('is')替换('i', 's') ('is') ? ,即输出Counter看起来 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我正在做此作业,现在我被困住了。 我不能用英语编程Bigram频率,不能用python 编程 “条件概率”吗?
也就是说,概率
令牌
给定前面的令牌
等于他们的二元组或两个标记同时出现的概率
,除以前一个令牌的概率。
我有一个包含很多字母的文本,然后我计算出该文本中字母的概率,因此与文本中的字母相比,字母“ a”出现0.015%
。
这些字母来自^a-zA-Z
,我想要的是:
如何制作一个具有字母((alphabet)x(alphabet))长度的表格,以及如何计算每种情况的条件概率?
就像是:
[[(a|a),(b|a),(c|a),...,(z|a),...(Z|a)]
[(a|b),(b|b),(c|b),...,(z|b),...(Z|b)]
... ...
[(a|Z),(b|Z),(c|Z),...,(z|Z),...(Z|Z)]]
为此,我应该计算概率,例如:如果此时您拥有字母“ a”,那么得到字母“ a”的机会是多少,依此类推。
我无法开始,希望您能启动我,并希望我明确需要解决的问题。
假设您的文件没有其他标点符号(足够容易删除):
import itertools
def pairwise(s):
a,b = itertools.tee(s)
next(b)
return zip(a,b)
counts = [[0 for _ in range(52)] for _ in range(52)] # nothing has occurred yet
with open('path/to/input') as infile:
for a,b in pairwise(char for line in infile for word in line.split() for char in word): # get pairwise characters from the text
given = ord(a) - ord('a') # index (in `counts`) of the "given" character
char = ord(b) - ord('a') # index of the character that follows the "given" character
counts[given][char] += 1
# now that we have the number of occurrences, let's divide by the totals to get conditional probabilities
totals = [sum(count[i] for i in range(52)) for count in counts]
for given in range(52):
if not totals[given]:
continue
for i in range(len(counts[given])):
counts[given][i] /= totals[given]
我没有测试过,但这应该是一个好的开始
这是一个字典版本,应该更易于阅读和调试:
counts = {}
with open('path/to/input') as infile:
for a,b in pairwise(char for line in infile for word in line.split() for char in word):
given = ord(a) - ord('a')
char = ord(b) - ord('a')
if given not in counts:
counts[given] = {}
if char not in counts[given]:
counts[given][char] = 0
counts[given][char] += 1
answer = {}
for given, chardict in answer.items():
total = sum(chardict.values())
for char, count in chardict.items():
answer[given][char] = count/total
现在, answer
包含您追求的概率。 如果您想给定“ b”的概率为“ a”,请查看answer['b']['a']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.