我有一个文本文件,里面有一些句子。假设有三个句子 "拉胡尔从市场上退了出来","我们要去市场","市场上所有的商店都关门了"。
现在我需要计算 "市场 "这个词出现的距离。
这里是5和8,因为 "市场 "这个词出现在 "市场 "这个词第一次出现的5个词之后,以此类推。
我是用ltk单词tokenizer来获取单词的。其实我需要对语料库中存在的大部分单词进行。
如果你有一个按顺序排列的单词列表,你可以列举它们,然后做一个查找,键是单词,值是找到这些单词的索引列表。
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': []}