在数组中搜索和匹配元素

时间:2009-01-19 17:15:18

标签: arrays compare scripting-language

我有两张桌子。

在一个表中有两列,一列有ID,另一列是文档的摘要,长度约为300-500字。大约有500行。

另一个表只有一列和> 18000行。该列的每个单元格都包含一个独特的首字母缩写词,如NGF,EPO,TPO等。

我感兴趣的是一个脚本,它将扫描表1中的每个摘要,并识别其中的一个或多个首字母缩略词,这些缩略词也出现在表2中。

最后,程序将创建一个单独的表,其中第一列包含表1第一列的内容(即ID)以及与该ID相关联的文档中的首字母缩略词。

具有Python,Perl或任何其他脚本语言专业知识的人可以提供帮助吗?

3 个答案:

答案 0 :(得分:1)

在我看来,你正试图加入两个表格,其中首字母缩略词出现在摘要中。即(伪SQL):

SELECT acronym.id, document.id
FROM acronym, document
WHERE acronym.value IN explode(documents.abstract)

鉴于所需的语义,您可以使用最直接的方法:

acronyms = ['ABC', ...]
documents = [(0, "Document zeros discusses the value of ABC in the context of..."), ...]

joins = []

for id, abstract in documents:
    for word in abstract.split():
        try:
            index = acronyms.index(word)
            joins.append((id, index))
        except ValueError:
            pass # word not an acronym

这是一个简单的实施;然而,它有一个n立方的运行时间作为acronyms.index执行线性搜索(我们最大的数组,不少)。我们可以通过首先构建首字母缩略词的哈希索引来改进算法:

acronyms = ['ABC', ...]
documents = [(0, "Document zeros discusses the value of ABC in the context of..."), ...]

index = dict((acronym, idx) for idx, acronym in enumberate(acronyms))    
joins = []

for id, abstract in documents:
    for word in abstract.split():
        try
            joins.append((id, index[word]))
        except KeyError:
            pass # word not an acronym

当然,您可能需要考虑使用实际的数据库。这样您就不必手动实现连接。

答案 1 :(得分:0)

非常感谢您的快速反应。 我假设伪SQL解决方案是针对MYSQL等的。但它在Microsoft ACCESS中不起作用。

第二个和第三个是我假设的Python。我可以将首字母缩略词和文档作为输入文件提供吗? babru

答案 2 :(得分:0)

它在Access中不起作用,因为表的访问方式不同(例如首字母缩略词。[id])