python - 创建单词词典及其在句子中的上下文

标签 python

我有一个包含数十万个单词的 Python 列表。单词按照它们在文本中的顺序出现。

我希望创建一个字典,其中包含与包含该单词的字符串相关联的每个单词,以及出现在其前后的 2 个(比方说)单词。

例如列表:“This”“is”“an”“example”“sentence”

应该成为字典:

"This" = "This is an"
"is" = "This is an example"
"an" = "This is an example sentence"
"example" = "is an example sentence"
"sentence" = "an example sentence"

类似于:

WordsInContext = Dict()
ContextSize = 2
wIndex = 0
for w in Words:
    WordsInContext.update(w = ' '.join(Words[wIndex-ContextSize:wIndex+ContextSize]))
    wIndex = wIndex + 1

这可能包含一些语法错误,但即使这些错误得到纠正,我也确信这将是一种非常低效的方法。

有人可以建议更优化的方法吗?

最佳答案

我的建议:

words = ["This", "is", "an", "example", "sentence" ]

dict = {}

// insert 2 items at front/back to avoid
// additional conditions in the for loop
words.insert(0, None)
words.insert(0, None)
words.append(None)
words.append(None)

for i in range(len(words)-4):   
    dict[ words[i+2] ] = [w for w in words[i:i+5] if w]

关于python - 创建单词词典及其在句子中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241871/

相关文章:

python - 在 PIL/pillow 中处理二进制 PNG 图像

python - 进入集体 SVN 并使用 jarn.mkrelease

python - 在 python 中读取没有标题的 .img 医学图像

python - python 中 list.count( ) 的替代方法

python - 来自 Torchat-ID 的状态响应

python - 将 numpy unit8 原始数组直接转换为 float32

python - 展平 NumPy 数组列表?

python - 通过pip安装pygame报错

php - 弱类型语言的优点(和缺点)是什么?

python - 如何在Python中删除csv行中的重复单词?