keywords = ("banana", "apple", "orange", ...)
before = 50
after = 100
TEXT = "a big text string, i.e., a page of a book"
for k in keywords:
if k in TEXT:
#cut = portion of text starting 'beforeText' chars before occurrence of 'k' and ending 'afterText' chars after occurrence of 'k'
#finalcut = 'cut' with first and last WORDS trimmed to assure starting words are not cut in the middle
伙计们,你能帮我在上面的例子中编码cut
和{
考虑到我要处理大量的文本、大量的页面和可能要搜索的20多个关键字,什么是最有效的解决方案?在
可以使用^{} 查找字符串中的所有匹配项。每个匹配对象都有一个^{} 方法,可以用来计算字符串中的位置。您也不需要检查键是否在字符串中,因为
finditer
返回一个空的迭代器:regex会修剪所有内容,包括第一个非单词字符序列,以及最后一个非单词字符序列(如果文本中有新行,我添加了
re.MULTILINE
)这可以进一步改进,因为只有两次关键字可以出现在文本的开头或结尾,因此不应该删除。在
^{pr2}$你需要调整你的算法。如前所述,它是O(n*m),n是关键字的,而m是文本的长度。这不会很好地扩大规模。在
取而代之的是:
keywords
成为set
,而不是tuple
。您只关心针对keywords
的成员身份测试,而set成员身份测试是O(1)。在TEXT
。这比仅仅做split()
要复杂一些,因为您还需要处理删除标点/换行符的操作。在keywords
集中,请抓住它周围的标记并继续。在就这样。所以,一些伪代码:
其中,}的实现,或者如果您需要库解决方案,
window
是您选择的类似于here的滑动窗口实现,tokenize
要么是您自己的涉及split
和{ntlk.tokenize
。在相关问题 更多 >
编程相关推荐