我正在尝试构建没有跨过符号的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', '.')}
有关如何实现这一点的任何想法?谢谢你的帮助!
我不确定这是否正是你所需要的,但是这个函数会生成ngrams,它们最后只能包含停用词(在本例中为句点):
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