创建没有停用词的上下文词字典

Create dictionary of context words without stopwords

我正在尝试创建文本中的单词及其上下文的词典。上下文应该是出现在字符串中术语位置的 5 个单词 window(两边两个单词)内的单词列表。实际上,我想忽略输出向量中的停用词。

我的代码如下。我可以从字典的键中获取停用词,但不能从值中获取。

words = ["This", "is", "an", "example", "sentence" ]
stopwords = ["it", "the", "was", "of"]
context_size = 2


stripes = {word:words[max(i - context_size,0):j] for word,i,j in zip(words,count(0),count(context_size+1)) if word.lower() not in stopwords}
print(stripes)

输出是:

{'example': ['is', 'an', 'example', 'sentence'], 'sentence': ['an', 'example', 'sentence']}
words = ["This", "is", "a", "longer", "example", "sentence"]
stopwords = set(["it", "the", "was", "of", "is", "a"])
context_size = 2

stripes = []
for index, word in enumerate(words):
    if word.lower() in stopwords:
        continue
    i = max(index - context_size, 0)
    j = min(index + context_size, len(words) - 1) + 1
    context = words[i:index] + words[index + 1:j]
    stripes.append((word, context))

print(stripes)

我建议使用元组列表,以防万一一个词在 words 中出现不止一次,dict 不只包含最后一个覆盖之前的词。我也会将停用词放在一个集合中,特别是如果它是一个更大的列表,比如 NLTKs 停用词,因为这会加快速度。

我也从上下文中排除了这个词本身,但根据你想如何使用它,你可能想要包括它。

这导致:

[('This', ['is', 'a']), ('longer', ['is', 'a', 'example', 'sentence']), ('example', ['a', 'longer', 'sentence']), ('sentence', ['longer', 'example'])]