使用re模块在txt文件中获取特定的重复部分

问题描述 投票:0回答:1

如何使用re模块在文本文件的开头和结尾复制重复的段落,并在列表的索引中插入每个段落

段落的例子

RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
python
1个回答
0
投票

除了语言障碍,根据您的标准尝试这一点

>>> import re

>>> string = '''RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2'''


>>> configs = re.findall('(?i)RemoteConfig[\S\s]*?ssh2(?=\s|$)', string)


>>> for config in configs:
        print(config)

#Output
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2
RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2




>>> configs

#Output
['RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140116/cleanup/stat_KSHA500 --conf /export/home-V cisco -N -S -o -P telnet,ssh2', 'RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_140200/cleanup/stat_KSHA11 --conf /export/home-V cisco -N -S -o -P telnet,ssh2', 'RemoteConfig cleanup.txt --prefix  /tftpboot/sites --status  /tftpboot/190315_1500/cleanup/stat_KSHA211 --conf /export/home-V cisco -N -S -o -P telnet,ssh2']
© www.soinside.com 2019 - 2024. All rights reserved.