如何处理 n-gram 和 Python 中的 max 函数的关系?

How to handle ties with n-grams and the max function in Python?

在我的程序中,我正在寻找 n-gram 并打印出数据集中有多少。 https://en.wikipedia.org/wiki/N-gram 对于那些不知道 n-gram 是什么的人。

这是我的代码:

from collections import defaultdict
import sys
from string import punctuation
def tokenize(text, ngrams=1):
    tokens = text.split()
    return [tuple(tokens[i:i+ngrams]) for i in range(len(tokens)-ngrams+1)]

line = ""
for i in sys.stdin:
    stripped = i.strip(punctuation)
    line += stripped.lower()
for n in range(1, 10):
    a = tokenize(line, n)
    d = defaultdict(int)
    for i in a:
        d[i] += 1
    result = max(d.items(), key = lambda x: x[1])
    if(result[1] >= 3):
        s = ' '.join(result[0])
        print('{:<6} {:<0} {:<0} {:<10}'.format(str(result[1]), str(n) + "-grams ", "|", s))

这是我的程序使用数据集的示例输出:

10     1-grams  | and
3      2-grams  | balloonman whistles
3      3-grams  | balloonman whistles far
3      4-grams  | balloonman whistles far and
3      5-grams  | balloonman whistles far and wee

这是我应该得到的(忽略格式差异):

10 1-grams       | and
3 2-grams        | balloonman whistles
3 2-grams        | whistles far
3 2-grams        | far and
3 2-grams        | and wee
3 3-grams        | balloonman whistles far
3 3-grams        | whistles far and
3 3-grams        | far and wee
3 4-grams        | balloonman whistles far and
3 4-grams        | whistles far and wee
3 5-grams        | balloonman whistles far and wee

问题似乎是当我在我的 defaultdict 中找到我的项目的最大值时,我只得到了 3 个 3-gram 中的一个,但我想得到所有 3 个 3-gram。有任何想法吗?提前谢谢你

是的,就是这个原因。来自 https://docs.python.org/3/library/functions.html#max

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

只需找到您正在做的最大值,然后使用最大值即结果[1],并获得最常见的 n 克的完整列表,以及列表理解。