我有两个文件:一个文件每行有一个单词,另一个文件有3个;它们如下所示:
列表文件:
Gene1
Gene2
Gene3
Gene4
主文件:
^{pr2}$所以我想要的是使用列表文件来搜索和提取主文件中与列表匹配的行,并将它们写入第三个新文件中。因此,期望的输出是:
新文件:
Gene8 Gene3 2.1
Gene1 Gene20 2.1
Gene3 Gene2 3.3
我尝试过使用正则表达式搜索,但我似乎没有正确理解,因为它总是在匹配的情况下编写整个文档,而不是单个匹配行。在
我尝试加载文件并将它们转换为字符串,并使用双for循环,但看起来它是逐字匹配的,这使得输出文件很难管理。在
是的,我看到了帖子Use Python to search lines of file for list entries,但我不能让它正常工作,结果文件还需要更多的格式化,使过程变得复杂,我似乎丢失了一些信息(列表文件有数千条条目,主文件有几十万行,所以不容易跟踪)。在
我来找你,因为我知道应该有一个更高效、更简单的方法来做,因为它需要运行几次
将关键字列表加载到集合中:
然后迭代主文件中的每一行,拉出至少包含一个关键字的行:
^{pr2}$这应该行。我使用了您提供的两个示例数据文件,下面的代码提供了您发布的所需输出。如果这个过程要经常重复,并且您需要加快速度,那么您可能需要考虑使用不同的搜索算法。如果是这样的话,请告诉我最常见的操作是什么(插入列表、搜索列表、删除列表中的项目),然后我们可以使用最合适的搜索算法。在
相关问题 更多 >
编程相关推荐