首页 > 解决方案 > 如何处理与 n-gram 和 Python 中的 max 函数的关系?

问题描述

在我的程序中,我正在查找 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

问题似乎是当我在我的默认字典中找到我的最大项目时,我只得到了 3 个 3 克中的一个,但我想得到所有 3 个 3 克。有任何想法吗?先感谢您

标签: pythonmaxn-gram

解决方案


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

如果多个项目是最大的,该函数返回遇到的第一个。这与其他排序稳定性保持工具一致,例如 sorted(iterable, key=keyfunc, reverse=True)[0] 和 heapq.nlargest(1, iterable, key=keyfunc)。

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


推荐阅读