【问题标题】:NLTK makes it easy to compute bigrams of words. What about letters?NLTK 使计算单词的二元组变得容易。字母呢?
【发布时间】:2013-01-05 04:33:41
【问题描述】:

我在网络上看到了大量关于 python NLTK 如何轻松计算二元组单词的文档。

字母呢?

我想做的是插入字典,让它告诉我不同​​字母对的相对频率。

最后我想做某种马尔可夫过程来生成看起来可能(但假的)单词。

【问题讨论】:

  • 您可以做的只是获取您的单词字符串,但让您的分词器按字母而不是按单词进行分词,然后在该字母令牌集上运行您的二元模型。

标签: python nlp nltk n-gram


【解决方案1】:

这是一个使用 collections 模块中的计数器的示例(模相对频率分布):

#!/usr/bin/env python

import sys
from collections import Counter
from itertools import islice
from pprint import pprint

def split_every(n, iterable):
    i = iter(iterable)
    piece = ''.join(list(islice(i, n)))
    while piece:
        yield piece
        piece = ''.join(list(islice(i, n)))

def main(text):
    """ return ngrams for text """
    freqs = Counter()
    for pair in split_every(2, text): # adjust n here
        freqs[pair] += 1
    return freqs

if __name__ == '__main__':
    with open(sys.argv[1]) as handle:
        freqs = main(handle.read()) 
        pprint(freqs.most_common(10))

用法:

$ python 14168601.py lorem.txt
[('t ', 32),
 (' e', 20),
 ('or', 18),
 ('at', 16),
 (' a', 14),
 (' i', 14),
 ('re', 14),
 ('e ', 14),
 ('in', 14),
 (' c', 12)]

【讨论】:

    【解决方案2】:

    如果您只需要二元组,则不需要 NLTK。你可以简单地这样做:

    from collections import Counter
    text = "This is some text"
    bigrams = Counter(x+y for x, y in zip(*[text[i:] for i in range(2)]))
    for bigram, count in bigrams.most_common():
        print bigram, count
    

    输出:

    is 2
    s  2
    me 1
    om 1
    te 1
     t 1
     i 1
    e  1
     s 1
    hi 1
    so 1
    ex 1
    Th 1
    xt 1
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2022-06-21
      相关资源
      最近更新 更多