python引用另一个文件中的列表_使用一个文件在Python中搜索另一个文件中的行

这段Python代码演示了如何从'master.txt'文件中读取每一行,并检查是否存在'list.txt'文件中的词汇。找到匹配项后,将这些行写入新的'new_file.txt'。它使用简单的线性搜索,适用于小规模数据,但对于大量数据,可能需要更高效的算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值