我有一系列出现在较大文本中的短语。我想强调这些短语,但我想先压缩这些短语。我使用 Python 3.5 和 NLTK 进行大部分处理。
例如,如果我有这句话:
The quick brown fox jumped over the lazy dog
和短语
brown fox
quick brown fox
我希望生成的 HTML 看起来像
The <b>quick brown fox</b> jumped over the lazy dog
不是
The <b>quick <b>brown fox</b></b> jumped over the lazy dog
似乎我应该能够制作某种列表理解,删除列表中其他项目的子集的项目,但我似乎无法完全理解它。关于如何折叠我的短语以删除其他条目的子集有什么想法吗?
请您参考如下方法:
如果术语在列表中列出:
terms = ['brown fox', 'quick brown', 'quick brown fox']
我会通过检查 term 列表本身来创建一个子集列表,并收集列表中其他术语子集的所有术语:
subsets = []
for x in terms:
for y in terms:
if x in y and x != y:
subsets.append(x)
或使用列表理解:
subsets = [x for x in terms for y in terms if x in y and x != y]
然后从术语列表中删除所有已知的子集:
phrases = [x for x in terms if x not in subsets]
或者在一行中(可能不推荐,因为它很难读):
phrases = [z for z in terms if z not in [x for x in terms for y in terms if x in y and x != y]]
应该给你:
>>> print(phrases)
['quick brown fox']
