使用一个文件在Python中搜索另一个文件中的行

2024-09-28 03:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件:一个文件每行有一个单词,另一个文件有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,但我不能让它正常工作,结果文件还需要更多的格式化,使过程变得复杂,我似乎丢失了一些信息(列表文件有数千条条目,主文件有几十万行,所以不容易跟踪)。在

我来找你,因为我知道应该有一个更高效、更简单的方法来做,因为它需要运行几次


Tags: 文件字符串文档列表for情况单词pr2
2条回答

将关键字列表加载到集合中:

keywords = set()
with open(list_file_path) as list_file:
    for line in list_file:
        if line.strip():
            keywords.add(line.strip())

然后迭代主文件中的每一行,拉出至少包含一个关键字的行:

^{pr2}$

这应该行。我使用了您提供的两个示例数据文件,下面的代码提供了您发布的所需输出。如果这个过程要经常重复,并且您需要加快速度,那么您可能需要考虑使用不同的搜索算法。如果是这样的话,请告诉我最常见的操作是什么(插入列表、搜索列表、删除列表中的项目),然后我们可以使用最合适的搜索算法。在

# open the list of words to search for
list_file = open('list.txt')

search_words = []

# loop through the words in the search list
for word in list_file:

    # save each word in an array and strip whitespace
    search_words.append(word.strip())

list_file.close()

# this is where the matching lines will be stored
matches = []

# open the master file
master_file = open('master.txt')

# loop through each line in the master file
for line in master_file:

    # split the current line into array, this allows for us to use the "in" operator to search for exact strings
    current_line = line.split()

    # loop through each search word
    for search_word in search_words:

        # check if the search word is in the current line
        if search_word in current_line:

            # if found then save the line as we found it in the file
            matches.append(line)

            # once found then stop searching the current line
            break

master_file.close()


# create the new file
new_file = open('new_file.txt', 'w+')

# loop through all of the matched lines
for line in matches:

    # write the current matched line to the new file
    new_file.write(line)

new_file.close()

相关问题 更多 >

    热门问题