提问人:SammySaucer 提问时间:1/23/2022 最后编辑:SammySaucer 更新时间:2/7/2022 访问量:583
使用 Python 为行中的文本添加引号
Adding quotes to text in line using Python
问:
我正在使用 Visual Studio Code 将文本替换为 Python。 我正在使用带有原始文本的源文件并将其转换为具有新文本的新文件。
我想在下文的新案文中加上引号。例如:
原文:set vlans xxx vlan-id xxx
新文本:(在行的剩余部分添加引号,如下所示)vlan xxx name "xxx"
这是我的代码:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
fout.write(line)
有没有办法在“name”后面的行中为文本添加引号?
编辑:
我尝试了这段代码:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
words = line.split()
words[-1] = '"' + words[-1] + '"'
line = ' '.join(words)
fout.write(line)
并收到此错误:
line 124, in <module>
words[-1] = '"' + words[-1] + '"'
IndexError: list index out of range
我也尝试了这段代码,但没有成功:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
import re
t = 'set vlans xxx vlan-id xxx'
re.sub(r'set vlans(.*)vlan-id (.*)', r'vlan\1names "\2"', t)
'vlan xxx names "xxx"'
同样,我的目标是自动在行尾的字符(vlan 编号)上添加双引号。
例如:
原文: set protocols mstp configuration-name Building 2021.Rm402.access.mstp.zzz
所需文本:set protocols mstp configuration-name “Building 2021.Rm402.access.mstp.zzz”
答:
使用以下正则表达式:
>>> import re
>>> t = 'set vlans xxx vlan-id xxx'
>>> re.sub(r'set vlans(.*)vlan-id (.*)', r'vlan\1names "\2"', t)
'vlan xxx names "xxx"'
搜索模式(第一个参数)中的括号用于创建可在替换模式(第二个参数)中使用的组。因此,搜索模式中的第一个匹配项将通过以下方式包含在替换模式中;第二个也是如此。(.*)
\1
编辑: 我分享的代码只是如何使用正则表达式的一个示例。以下是您应该如何使用它。
import re
# whatever imports and code you have down to...
with open("SanitizedFinal_E4300.txt", "rt") as fin, open("output6.txt", "wt") as fout:
for line in fin:
line = re.sub(r'set vlans(.*)vlan-id (.*)', r'vlan\1names "\2"', line)
fout.write(line)
重要说明:如果需要修改的行的格式与共享的原始文本示例有任何不同,则需要对正则表达式进行调整。
首先,我们将文本拆分为单词,方法是用空格拆分它们(这是默认的)。split
然后,我们取最后一个单词,给它加上引号,然后用每个单词之间的空格将其连接在一起:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
words = line.split()
# print(words) # ['vlan', 'xxx', 'name', 'xxx']
if words: # if the line is empty, just output the empty line
words[-1] = '"' + words[-1] + '"'
line = ' '.join(words)
# print(line) # vlan xxx name "xxx"
fout.write(line)
警告:在您的问题中,您说您希望输出在第一个空格之后有两个空格。此结果每个单词之间只有一个空格。vlan xxx name "xxx"
xxx
评论
split
join
\1
\2
re.sub()