如何在 python 中按 n-gram 对字符串列表进行排序

How to sort list of string by n-grams in python

您好,我想按照 n-gram 的降序对字符串列表进行排序。

假设以下是我的列表

["sedan", "sail sedan", "sail", "price of", "price", "of chevrolet", "of", "chevrolet sail", "chevrolet"]

我要输出

["price of", "of chevrolet", "chevrolet sail", "sail sedan", "sedan",  "sail",  "price",  "of", "chevrolet"]

注: 没有按字母顺序验证。

假设 "descending order of n-grams" 你的意思是你想要拥有,例如首先是所有的 3 克,然后是 2 克,等等,你可以试试这个:

>>> ngrams = ["sedan", "sail sedan", "sail", "price of", "price", "of chevrolet", "of", "chevrolet sail", "chevrolet"]
>>> sorted(ngrams, key=lambda s: len(s.split()), reverse=True)
['sail sedan', 'price of', 'of chevrolet', 'chevrolet sail', 'sedan', 'sail', 'price', 'of', 'chevrolet']

这使用了一个特殊的 key 函数,首先 split 字符串然后使用 len 来确定 n-gram 中的单词数。或者,您也可以尝试 counting n-gram 中的空格数:

>>> sorted(ngrams, key=lambda s: s.count(" "), reverse=True)