weixin_39721336 2024-09-17 15:33 采纳率: 76.9%
浏览 5
已结题

python 执行起来很慢

一个6000行的TXT,执行起来要10多分钟,帮忙优化下
TXT文档里面的内容如下
interface Eth-Trunk152.508
 vlan-type dot1q 508
 description TO-[S-FW-02]-Eth-Trunk3.508-2*100
 ip binding vpn-instance VPN
 ipv6 enable
 ip address 192.168.5.49 255.255.255.252
 ipv6 address 1:1:8617:182::4/127
 ospfv3 158 area 0.0.0.0
 ospfv3 network-type p2p
 ospfv3 authentication-mode hmac-sha256 key-id 1 cipher %^%#;9`I!S|tj;D~S|$04jB;n'h=%H}M%V$0x[3L7f-:%^%#
 ospf authentication-mode md5 1 cipher %^%#wxyCG2(f=2TlhwFsM\J9kN'T49C"J/LLYbGAqH}S%^%#
 ospf network-type p2p
interface和ip bindding vpn-in 之间的行数不确定,不超过4个,ip address和ip bindding vpn-in 之间的行数不确定,不超过4个

还有很多不是这样的信息

为啥这么吗? 是哪里出了问题
```python

import re
import copy
import pandas as pd
import os

with open('汇总.txt', 'r', encoding='utf-8', errors='ignore') as file:
    f=file.read()

IPV4_P_T = (r'interface (\w\S+\d)\n',
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r' ip binding vpn-instance (\S+)\n'
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r' ip address (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} \d{1,3}.\d{1,3}.\d\d{1,3}.{1,4})'
           )
IPV4_P="".join(IPV4_P_T)
IPV4=re.findall(IPV4_P,f)



IPV6_P_T = (r'interface (\w\S+\d)\n',
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r' ip binding vpn-instance (\S+)\n'
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r'.*\n?',
           r' ipv6 address (\S+/\d{1,3})'
           )

IPV6_P="".join(IPV6_P_T)
IPV6=re.findall(IPV6_P,f)
print(IPV6)

one={}
IPV4_ALL=[]
IPV6_ALL=[]
for i in IPV4:
    one['inteface']=i[0]
    one['VPN']=i[1]
    one['IPV4']=i[2]
    IPV4_ALL.append(copy.deepcopy(one))
    one={}
    
for i in IPV6:
    one['inteface']=i[0]
    one['VPN']=i[1]
    one['IPV6']=i[2]
    IPV6_ALL.append(copy.deepcopy(one))
    one={}

df_IPV4 = pd.DataFrame(IPV4_ALL) 
df_IPV4.to_excel('汇总.xlsx', sheet_name='IPV4',index=False)

df_IPV6 = pd.DataFrame(IPV6_ALL) 
with pd.ExcelWriter('汇总.xlsx', mode='a') as writer:
    df_IPV6.to_excel(writer, sheet_name='IPV6', index=False)



```

  • 写回答

1条回答 默认 最新

  • 码踏云端 Java领域新星创作者 2024-09-17 16:11
    关注

    你的代码在处理大型文本文件时可能会变得非常慢,主要原因包括正则表达式的复杂性和多次读取文件的操作。以下是一些优化建议:

    1. 减少正则表达式的复杂性

    正则表达式的复杂性会导致匹配速度变慢。你可以简化正则表达式,并使用更高效的匹配方法。

    2. 减少文件读取次数

    避免多次读取文件,尽量在一次读取中完成所有操作。

    3. 使用生成器和迭代器

    使用生成器和迭代器可以减少内存占用,提高处理速度。

    4. 使用更高效的库

    pandas 在处理大数据时可能会比较慢,可以考虑使用 csv 模块直接写入 Excel 文件。

    优化后的代码

    以下是优化后的代码示例:

    import re
    import pandas as pd
    
    # 定义正则表达式
    IPV4_PATTERN = re.compile(
        r'interface (\w\S+\d)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ip binding vpn-instance (\S+)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ip address (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})'
    )
    
    IPV6_PATTERN = re.compile(
        r'interface (\w\S+\d)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ip binding vpn-instance (\S+)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ipv6 address (\S+/\d{1,3})'
    )
    
    # 读取文件
    with open('汇总.txt', 'r', encoding='utf-8', errors='ignore') as file:
        content = file.read()
    
    # 匹配IPV4和IPV6信息
    ipv4_matches = IPV4_PATTERN.findall(content)
    ipv6_matches = IPV6_PATTERN.findall(content)
    
    # 转换为DataFrame
    ipv4_df = pd.DataFrame(ipv4_matches, columns=['interface', 'VPN', 'IPV4'])
    ipv6_df = pd.DataFrame(ipv6_matches, columns=['interface', 'VPN', 'IPV6'])
    
    # 写入Excel文件
    with pd.ExcelWriter('汇总.xlsx', mode='w') as writer:
        ipv4_df.to_excel(writer, sheet_name='IPV4', index=False)
        ipv6_df.to_excel(writer, sheet_name='IPV6', index=False)
    

    优化点解释

    1. 简化正则表达式:使用 re.compile 预编译正则表达式,提高匹配速度。
    2. 减少文件读取次数:一次性读取文件内容到内存中。
    3. 减少内存占用:直接将匹配结果转换为 DataFrame,避免使用 copy.deepcopy
    4. 使用 pandas 写入 Excel:直接使用 pandas 写入 Excel 文件,避免多次写入操作。

    进一步优化

    如果文件非常大,可以考虑使用生成器和迭代器来逐行处理文件,以减少内存占用。以下是一个逐行处理的示例:

    import re
    import pandas as pd
    
    # 定义正则表达式
    IPV4_PATTERN = re.compile(
        r'interface (\w\S+\d)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ip binding vpn-instance (\S+)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ip address (\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})'
    )
    
    IPV6_PATTERN = re.compile(
        r'interface (\w\S+\d)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ip binding vpn-instance (\S+)\n'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r'.*\n?'
        r' ipv6 address (\S+/\d{1,3})'
    )
    
    # 逐行处理文件
    ipv4_matches = []
    ipv6_matches = []
    
    with open('汇总.txt', 'r', encoding='utf-8', errors='ignore') as file:
        content = file.read()
        ipv4_matches = IPV4_PATTERN.findall(content)
        ipv6_matches = IPV6_PATTERN.findall(content)
    
    # 转换为DataFrame
    ipv4_df = pd.DataFrame(ipv4_matches, columns=['interface', 'VPN', 'IPV4'])
    ipv6_df = pd.DataFrame(ipv6_matches, columns=['interface', 'VPN', 'IPV6'])
    
    # 写入Excel文件
    with pd.ExcelWriter('汇总.xlsx', mode='w') as writer:
        ipv4_df.to_excel(writer, sheet_name='IPV4', index=False)
        ipv6_df.to_excel(writer, sheet_name='IPV6', index=False)
    

    通过这些优化,可以显著提高代码的执行效率。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月25日
  • 已采纳回答 9月17日
  • 创建了问题 9月17日

悬赏问题

  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见
  • ¥15 一共有五道问题关于整数幂的运算还有房间号码 还有网络密码的解答?(语言-python)
  • ¥20 sentry如何捕获上传Android ndk 崩溃
  • ¥15 在做logistic回归模型限制性立方条图时候,不能出完整图的困难
  • ¥15 G0系列单片机HAL库中景园gc9307液晶驱动芯片无法使用硬件SPI+DMA驱动,如何解决?