[英]How to print the probability of each bigram in table format
我要打印的确切格式如下:
Bigram MLE Prob Bigram Prob
"interesting news" 0.000xxxx 0.000xxx
"interesting show" 0.000xxxx 0.000x
..(any bigram word set in the text)...
....
...
下面是我的代码。
from __future__import division
import re
import string
f = open("C:\Python27\text.txt", "rU")
rawtext = f.read()
bigrams = {}
words_punct = rawtext.split()
words = [ w. strip(string.punctuation).lower() for w in words_punct ]
words = ["START"] + words + ["END"]
for index, word in enumerate(words):
if index < len(words) - 1:
w1 = words[index]
w2 = words[index + 1]
bigram = (w1, w2)
if bigram in bigrams:
bigrams[ bigram ] = bigrams[ bigram ] + 1
else:
bigrams[ bigram ] = 1
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
for bigram, count in sorted_bigrams:
Bi_Prob = count / sum(list(bigrams.values()))
print Bi_Prob
这给了我每个二元组的Bi_Prob。 (即0.000xxx,0.0000xxx,0.0000x....。)我对Python不太了解,因此我在这里有很多帮助,无论如何我都可以很快制作变量MLE Prob ..但是我很难以表格格式打印。.我尝试了制表模块,如下所示。
from tabulate import tabulate
for bigram in sorted_bigrams:
print tabulate([[bigram]], headers = ['Bigram']
像这样的东西...但是它不起作用...这意味着,使用制表模块,我可以获得我之前说过的确切打印结果,但是它只包含一个数据。 我想要一些循环结果...每个bigram,都应将其概率插入表格表格中...
帮助我,也给我一些其他建议。
ps我没有在这里使用nltk。 但是我还是安装了它。 但不知道如何使用。 我听说nltk可以减轻我的生活...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.