如何使用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
答案 0 :(得分: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']