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

Python提取文本中localpref及其对应值的问题求助

问题描述

我把一份重复4次的BGP路由输出内容保存到文本文件中,需要提取所有包含localpref的行里的localpref及其对应的数值,期望每行输出格式为localpref 数值。但我写的Python代码运行后只输出{'localpref'} {'o'},求帮忙排查错误并修正。

文本内容

x.x.x.x/xx         *[BGP/170] 5d 12:05:08, MED 100, localpref 300, from x.x.x.x
                    >  to x.x.x.x via et-0/1/5.0
                    [BGP/170] 5d 12:05:08, MED 100, localpref 300
                    >  to x.x.x.x via et-0/1/5.0
                    [BGP/170] 1w3d 23:49:43, MED 100, localpref 300, from x.x.x.x
                    >  to x.x.x.x via ae0.0
                    [BGP/170] 1w3d 23:49:43, localpref 90
                    >  to x.x.x.x via ae3.0

期望输出

localpref 300
localpref 300
localpref 300
localpref 90
localpref xx
localpref xx
...

编写的代码

with open(r'Output.txt', 'r') as LP:
   word = 'localpref'
   all_data = LP.readlines()
   for line in all_data:
       if line.find(word) != -1:
        list_of_words = line
        localpref_and_value = list_of_words[list_of_words.index(word) + 1]
        now = datetime.now()
        print(now)
        print('-'*65)
        print('Local preferences found')
        print({word},{localpref_and_value})
        print('-'*65)

实际输出

Local preferences found
{'localpref'} {'o'}

错误排查与修正

错误原因

  • 未拆分行内容为单词列表:代码中list_of_words = line只是将整行字符串赋值给变量,没有拆分出独立单词。后续list_of_words.index(word) + 1取的是字符串中localpref起始索引+1的单个字符,而非对应的数值。
  • 集合格式输出错误:print({word},{localpref_and_value})将变量放入集合中,导致输出为集合格式而非目标文本格式。
  • 缺少模块导入:代码使用datetime.now()但未导入datetime模块,运行时会触发报错。

修正后的代码

import datetime

with open(r'Output.txt', 'r') as LP:
    target_word = 'localpref'
    for line in LP:
        line = line.strip()
        if target_word in line:
            # 替换逗号并按空格拆分,确保localpref和数值为独立元素
            parts = line.replace(',', '').split()
            if target_word in parts:
                idx = parts.index(target_word)
                # 确保存在后续数值
                if idx + 1 < len(parts):
                    value = parts[idx + 1]
                    now = datetime.now()
                    print(now)
                    print('-'*65)
                    print('找到本地优先级')
                    print(f'{target_word} {value}')
                    print('-'*65)

简化版(仅保留核心输出)

如果不需要时间戳和分隔线,可简化为:

with open(r'Output.txt', 'r') as LP:
    target_word = 'localpref'
    for line in LP:
        if target_word in line:
            parts = line.replace(',', '').split()
            idx = parts.index(target_word)
            if idx + 1 < len(parts):
                print(f'{target_word} {parts[idx + 1]}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:14:59