【问题标题】:Distance between occurrences of a word单词出现之间的距离
【发布时间】:2020-05-16 21:08:01
【问题描述】:

我有一个包含一些句子的文件。假设有三个句子“Rahul 从市场支持。”,“我们要去市场”,“市场上所有的商店都关门了。”

现在我需要计算“市场”一词出现之间的距离。

这里应该是 5 和 8,因为“market”这个词出现在“market”这个词第一次出现的 5 个词之后,依此类推。

我正在使用 nltk 单词标记器来获取单词。实际上,我需要对语料库中存在的大部分单词进行此操作。

【问题讨论】:

  • 给您带来麻烦的代码在哪里?这似乎是简单的字符串处理,根本不是 NLP 问题......对于这个任务。

标签: python nlp nltk python-re


【解决方案1】:

如果您按顺序排列了单词列表,则可以枚举它们并进行查找,其中键是单词,值是找到单词的索引列表:

import re
from collections import defaultdict

s = "Rahul backed from the market. We are going to market All the shops are closed in the market."

# using re for simplicity
words = re.findall(r'\w+', s)

positions = defaultdict(list)

for index, word in enumerate(words):
    positions[word].append(index)

positions 看起来像:

defaultdict(list,
        {'Rahul': [0],
         'backed': [1],
         'from': [2],
         'the': [3, 11, 16],
         'market': [4, 9, 17],
         'We': [5],
         'are': [6, 13],
         'going': [7],
         'to': [8],
         'All': [10],
         'shops': [12],
         'closed': [14],
         'in': [15]}) 

您可以通过压缩列表并减去索引来计算距离:

distances = {}

for word, l in positions.items():
    distances[word] = [m - n for n, m in zip(l, l[1:])]

现在distances 是单词之间距离的字典。只有一个词的项目是空列表,因为距离在这里没有意义:

{'Rahul': [],
 'backed': [],
 'from': [],
 'the': [8, 5],
 'market': [5, 8],
 'We': [],
 'are': [7],
 'going': [],
 'to': [],
 'All': [],
 'shops': [],
 'closed': [],
 'in': []}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-30
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2013-04-28
    相关资源
    最近更新 更多