You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python读取a.txt所有字符串并在b.txt中检索匹配内容

完整实现方案

实现思路

  • 优先将b.txt的所有行内容存入集合,利用集合O(1)的查询效率提升检索速度,避免每次查询都遍历b.txt全文件
  • 处理每行内容时仅移除末尾的换行符,保留行内原始的空格、特殊字符等,保证匹配准确性

完整代码

#!/usr/bin/python3
# 加载b.txt所有内容到集合
b_lines = set()
with open('b.txt', 'r', encoding='utf-8') as second:
    for line in second:
        # 仅去掉末尾换行符,不修改行内其他内容
        processed_line = line.rstrip('\n')
        b_lines.add(processed_line)

# 逐行校验a.txt内容
with open('a.txt', 'r', encoding='utf-8') as first:
    for line in first:
        processed_line = line.rstrip('\n')
        if processed_line in b_lines:
            print("true")

可选调整(按需使用)

如果只要存在任意匹配就输出一次true,不需要每条匹配都单独输出,可以替换校验部分的代码:

with open('a.txt', 'r', encoding='utf-8') as first:
    match_found = False
    for line in first:
        processed_line = line.rstrip('\n')
        if processed_line in b_lines:
            match_found = True
            break
    print("true" if match_found else "false")

样例运行结果

使用你提供的a.txt和b.txt样例运行,会输出一次true,对应a.txt中的a在b.txt中匹配成功。

内容的提问来源于stack exchange,提问作者thabo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:21:02