在python行中删除n个gram中的重复项

2024-05-29 05:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码生成n个gram,并且n个gram出现的计数数。 我有一个csv文件,其中的行和列包含每行的单词字符串。 这段代码例如,当它搜索得到一个4克的“这是我的小狗”时,它还会计算它在同一行中出现的次数。 我的意思是,当它在一行中出现n-gram时,它应该计数一次,在另一行中计算第二次,依此类推。在

e.g  row         Word
      1          this is my puppy what this is my puppy
      2          this is my puppy

所以这个代码把“这是我的小狗”算作3次。但我希望是2次

这是python代码

^{pr2}$

我们将非常感谢你的帮助。 谢谢你


Tags: 文件csv字符串代码ismythis单词
1条回答
网友
1楼 · 发布于 2024-05-29 05:09:02

您可以使用defaultdict,而不是半手工地填充ngrams

为了防止同一行中的同一个ngram dict计数两次,您必须为每行生成一个ngram dict,然后将其与普通ngram dict相结合

def count_ngrams(lines, min_length=4, max_length=5):
    """Iterate through given lines iterator (file object or list of
    lines) and return n-gram frequencies. The return value is a dict
    mapping the length of the n-gram to a collections.Counter
    object of n-gram tuple and number of times that n-gram occurred.
    Returned dict includes n-grams of length min_length to max_length.
    """
    lengths = range(min_length, max_length + 1)
    ngrams = collections.defaultdict(collections.Counter)
    queue = collections.deque(maxlen=max_length)

    # Helper function to add n-grams at start of current queue to dict
    def add_queue(ngrams_line):
        current = tuple(queue)
        for length in lengths:
            if len(current) >= length: 
                ngrams_line[length][current[:length]] = 1  # instead of += 1

    # to combine the 2 defaultdict(Counter)            
    def combine_ngrams(ngram, ngramline):
        for k, v in ngramsline.items():
            ngrams[k] += v
        return ngrams

    # Loop through all lines and words and add n-grams to dict
    for line in lines:
        ngrams_line = collections.defaultdict(collections.Counter)
        for word in tokenize(line):
            queue.append(word)
            if len(queue) >= max_length:
                    add_queue(ngrams_line)
        ngrams = combine_ngrams(ngrams, ngrams_line)


    # Make sure we get the n-grams at the tail end of the queue
    ngrams_line = collections.defaultdict(collections.Counter)
    while len(queue) > min_length:
        queue.popleft()
        add_queue(ngrams_line)
    ngrams = combine_ngrams(ngrams, ngrams_line)

    return ngrams

我不能100%理解while len(queue) > min_length:后面的部分,或者为什么{}没有重置每一行,你可能需要调整一下我的答案

相关问题 更多 >

    热门问题