最常见的2克使用python

stf*_*321 4 python n-gram python-2.7 python-collections pyspark

给定一个字符串:

this is a test this is
Run Code Online (Sandbox Code Playgroud)

我怎样才能找到最常见的2克?在上面的字符串中,所有2克都是:

{this is, is a, test this, this is}
Run Code Online (Sandbox Code Playgroud)

你可以注意到,2克this is出现了2次.因此结果应该是:

{this is: 2}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用Counter.most_common()方法来查找最常见的元素,但是如何从字符串开始创建一个2-gram的列表呢?

Mar*_*gur 6

您可以使用此博客文章中提供的方法在Python中方便地创建n-gram.

from collections import Counter

bigrams = zip(words, words[1:])
counts = Counter(bigrams)
print(counts.most_common())
Run Code Online (Sandbox Code Playgroud)

当然,这假设输入是单词列表.如果您的输入是一个类似于您提供的字符串(没有任何标点符号),那么您只需words = text.split(' ')获取单词列表即可.但是,一般而言,您必须考虑标点符号,空格和其他非字母字符.在这种情况下,你可能会做类似的事情

import re

words = re.findall(r'[A-Za-z]+', text)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用外部库,如nltk.tokenize.

编辑.如果您需要tri-gram或任何其他任何其他n-gram,那么您可以使用我链接到的博客文章中提供的功能:

def find_ngrams(input_list, n):
  return zip(*(input_list[i:] for i in range(n)))

trigrams = find_ngrams(words, 3)
Run Code Online (Sandbox Code Playgroud)