【发布时间】:2017-07-25 14:21:28
【问题描述】:
我正在尝试在文本字符串中搜索某些单词/字符串并将它们的位置放入字典中。
一个例子将更好地解释我想要完成什么以及我的问题是什么。
content = """Learning python is something I always wanted to do. The fact that python is a simple and intuitive language made me feel bad for learning other programming languages in the first place. I think the main reason why I didn't choose the python language was the fact that I didn't do a proper research about the pros and cons of the available programming options. I gues that writing this paragraph about learning the python language it's harder than the python script I'm trying to accomplish. No, I'm just kidding, if this was the case then I would have completed writing the python languaguage and didn't bother you guys anymore."""
mylist = ['python', 'dummy keyword', 'python language', 'learning the python language', 'another keyword']
dictKw = {}
for x in mylist:
x = x.lower()
listKw = []
for m in re.finditer(x, contentLower):
#print (x , " found " , m.start(), m.end())
listKwPos = []
listKwPos = [m.start(), m.end()]
listKw.append(listKwPos)
dictKw [x] = listKw
print dictKw
因此,我在这里为 mylist 中找到的每个关键字搜索 content 字符串,并将每次出现的开始和结束位置存储到具有关键字的字典中作为关键字位置的键和列表列表。
打印 dictKw 我得到:
{'python': [[9, 15], [66, 72], [234, 240], [414, 420], [451, 457], [574, 580]], 'learning the python language': [[401, 429]], 'python language': [[234, 249], [414, 429]]}
首先,我认为字典中的键顺序是错误的——python,学习python语言,python语言而不是python,python语言,学习python语言强>。我看到,当附加 listKw 列表时,它会将 learning the python language 键放在 python 和 python language 之间放在最后。
我认为正确的结果应该是:
{'python': [[9, 15], [66, 72], [234, 240], [414, 420], [451, 457], [574, 580]], 'python language': [[234, 249], [414, 429]], 'learning the python language': [[401, 429]]}
现在我想删除相互重叠的关键字的列表元素,保持 mylist
中第一个关键字的初始优先级在我们的示例中,python 与 python 语言 重叠,所以第一次发生这种情况时,python 语言 应该丢失第一个位置列表,所以结果是:
{'python': [[9, 15], [66, 72], [234, 240], [414, 420], [451, 457], [574, 580]], 'python language': [[414, 429]],'learning the python language': [[401, 429]]}
当检查剩余的重叠时,优先级应该改变,所以 python 会丢失重叠的列表元素,所以结果是:
{'python': [[9, 15], [66, 72], [234, 240], [451, 457], [574, 580]], 'python language': [[414, 429]],'learning the python language': [[401, 429]]}
等等。因此,如果我们遇到第三次重叠,优先级应该再次切换到 python,这样 python 语言 就会丢失开始/结束元素列表。
检查完成后,python 语言和学习 python 语言应进行重叠检查,导致删除 学习 python 语言的列表值 字典键。
最终结果应该是:
{'python': [[9, 15], [66, 72], [234, 240], [451, 457], [574, 580]], 'python language': [[414, 429]],'learning the python language': [[]]}
现在对于这个重叠的问题部分,我不知道从哪里开始,所以我请求你的帮助,为我指明正确的方向,或者为我想要完成的工作提供另一种方法。
请记住,mylist 元素可以有任何其他顺序,并且元素的顺序决定了关键字的优先级 - 最高的优先级最高。
【问题讨论】:
-
字典中的键没有定义顺序!所以,你不能说,有错误的顺序。打印 dict-Object 时,键值按随机顺序打印。
-
此外,您的示例似乎并不合理。一般在尽量避免重叠的时候,还应该考虑
python和python language的重叠,去掉python关键字的[414,420]-match!
标签: python python-2.7 list dictionary