【问题标题】:Counting bigram frequencies in python在python中计算二元组频率
【发布时间】:2017-10-07 04:57:49
【问题描述】:

假设我有一个看起来像这样的数据

['<s>', 'I' , '<s>', 'I', 'UNK', '</s>']

我想得到只出现一次的二元组数,所以

n1 == ('I', '<s>'), ('I', 'UNK'), ('UNK', '</s>')
len(n1) == 3 

以及出现两次的二元组数

n2 == ('<s>', 'I')
len(n2) == 1

我正在考虑将第一个单词存储为 sen[i],将下一个单词存储为 sen[i + 1],但我不确定这是否正确。

【问题讨论】:

  • 你有这种格式还是可以转换成列表格式?
  • nltk 有一个很好的 FreqDist 函数,应该对此非常有用。
  • 第一行不是有效的python。它应该是一个字符串吗?字符串列表?还有什么?请更正。
  • @altendky 对不起。它应该遍历字符串列表(语料库)

标签: python


【解决方案1】:

考虑您的清单:-

lis = ['<s>', 'I' , '<s>', 'I', 'UNK', '</s>']

遍历列表以生成二元组的元组并不断将它们的频率输入字典,如下所示:-

bigram_freq = {}
length = len(lis)
for i in range(length-1):
    bigram = (lis[i], lis[i+1])
    if bigram not in bigram_freq:
        bigram_freq[bigram] = 0
    bigram_freq[bigram] += 1

现在,像这样收集频率 = 1 和频率 = 2 的二元组:-

bigrams_with_frequency_one = 0
bigrams_with_frequency_two = 0
for bigram in bigram_freq:
    if bigram_freq[bigram] == 1:
        bigrams_with_frequency_one += 1
    elif bigram_freq[bigram] == 2:
        bigrams_with_frequency_two += 1

您的结果是 bigrams_with_frequency_one 和 bigrams_with_frequency_two。 希望对你有帮助!

【讨论】:

  • 那么,我们只要返回bigrams_with_frequency_one = [] bigrams_with_frequency_two = []的长度就可以得到频率了?
  • 哦,对不起,我的错……我没有注意到。这比我做的更容易......我正在编辑。如果有用请采纳我的回答。 :)
  • 这真的很有帮助。谢谢!
【解决方案2】:

你可以试试这个:

my_list = ['<s>', 'I' , '<s>', 'I', 'UNK', '</s>']

bigrams = [(l[i-1], l[i]) for i in range(1, len(my_list))]
print(bigrams)
# [('<s>', 'I'), ('I', '<s>'), ('<s>', 'I'), ('I', 'UNK'), ('UNK', '</s>')]

d = {}

for c in set(bigrams):
    count = bigrams.count(c)
    d.setdefault(count, []).append(c)

print(d)
# {1: [('I', '<s>'), ('UNK', '</s>'), ('I', 'UNK')], 2: [('<s>', 'I')]}

【讨论】:

    猜你喜欢
    • 2011-08-18
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 2021-07-28
    • 2021-09-21
    • 1970-01-01
    • 2013-11-27
    相关资源
    最近更新 更多