Skip to main content
 首页 » 编程设计

python之在 python 中创建基于关键字的搜索

2025年05月04日10java哥

我有一个巨大的 CSV 文件,其中包含近 6K 个条目,该文件看起来像这样:

PDB ID  NDB ID  Structure Title  Citation Title     Abstract 
1ET4    1ET4    Structure of     Solution structure Research was performed and  
                haemoglobin mRNA of mRNA aptamer    structure of mRNa was obtained 
                aptamer. 

我的最终目标是显示给定关键字的输出,如下所示:

Keyword: mRNA 
PDB ID   NDB ID   Structure Title   Citation Title   Abstract   Location of first hit 
                                                                struc/citation/abstract 

我的起点是什么?另外,我是否必须为此使用称为 Regex 的东西?

免责声明:这是研究项目的一部分,而不是学校作业。

伪代码或模板对我来说会很棒。

请您参考如下方法:

您可以解析 CSV 文件并创建两个数据结构。两个字典。

一个字典将包含每一行,以 PDB ID 为关键字。另一个字典将存储多组 PDB ID 并以关键字为关键字。

下面只是示例代码,因为我忽略了 header 。您可能想正确解析 csv...

from collections import defaultdict 
entries = {} 
keywords = defaultdict(set) 
 
with open('my_csv.csv') as f: 
    for line in f: 
        entries[line.split()[0]] = line  # so keying on the PDB ID 
 
with open('my_csv.csv') as f: 
    for line in f: 
        for kw in line.split()[1:] 
            keywords[kw].add(line.split()[0]) 

一旦你有了这两个数据结构,在关键字字典中查找关键字、遍历集合并打印出具有相关 PDB id 的每一行应该是微不足道的。