在python

时间:2019-02-26 12:22:02

标签: python list split divide

我正在尝试构建不跨越句号的n-gram。 Split()仅适用于函数,list [index]仅适用于索引。有没有一种方法可以通过给它一个字符串/元素来访问/分割/划分一个列表?这是我当前功能的一个片段:

text = ["split","this","stuff",".","my","dear"]

def generate_ngram(rawlist, ngram_order):
        """
        Input: List of words or characters, ngram-order ["this", "is", "an", "example"], 2
        Output: Set of tuples or words or characters {("this", "is"),("is","an"),...}
        """

    list_of_tuples = []
    for i in range(0, len(rawlist) - ngram_order + 1):
        ngram_order_index = i + ngram_order    
        generated_ngram = rawlist[i : ngram_order_index]

        #if "." in generated_ngram:
            #generated_ngram . . . 

        generated_tuple = tuple(generated_ngram)  
        list_of_tuples.append(generated_tuple)

    return set(list_of_tuples)

generate_ngram(text,3)

当前返回:

{('.', 'my', 'dear'),
 ('stuff', '.', 'my'),
 ('split', 'this', 'stuff'),
 ('this', 'stuff', '.')}

但理想情况下应返回:

{('split', 'this', 'stuff'),
 ('this', 'stuff', '.')}

关于如何实现这一目标的任何想法?感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我不确定这是否正是您所需要的,但是此函数生成的ngram只能在最后包含停用词(在这种情况下为句点):

STOPWORDS = {"."}

def generate_ngram(rawlist, ngram_order):
    # All ngrams
    ngrams = zip(*(rawlist[i:] for i in range(ngram_order)))
    # Generate only those ngrams that do not contain stop words before the end
    return (ngram for ngram in ngrams if not any(w in STOPWORDS for w in ngram[:-1]))

text = ["split", "this", "stuff", ".", "my", "dear"]
print(*generate_ngram(text, 3), sep="\n")
# ('split', 'this', 'stuff')
# ('this', 'stuff', '.')
print(*generate_ngram(text, 2), sep="\n")
# ('split', 'this')
# ('this', 'stuff')
# ('stuff', '.')
# ('my', 'dear')

请注意,此函数返回一个生成器。您可以根据需要将其转换为包含list(...)的列表,也可以直接对其进行迭代。

编辑:您可能会发现下面的等效语法更易读。

def generate_ngram(rawlist, ngram_order):
    # Iterate over all ngrams
    for ngram in zip(*(rawlist[i:] for i in range(ngram_order))):
        # Yield only those not containing stop words before the end
        if not any(w in STOPWORDS for w in ngram[:-1]):
            yield ngram