I am using Visual Studio Code to replace text with Python. I am using a source file with original text and converting it into a new file with new text.
I would like to add quotes to the new text that follows. For example:
Original text: set vlans xxx vlan-id xxx
New text: vlan xxx name "xxx" (add quotes to the remaining portion of the line as seen here)
Here is my code:
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)
Is there a way to add quotes for text in the line that follows 'name'?
CodePudding user response:
Use the following regular expression:
>>> 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"'
The parentheses in the search pattern (first parameter) are used to create groups that can be used in the replacement pattern (second parameter). So the first (.*) match in the search pattern will be included in the replacement pattern by means of \1; same thing goes with the second one.
CodePudding user response:
First, we split the text up into words by splitting them by whitespace (which is what split does by default).
Then, we take the last word, add quotes to it, and join it back together with a space between each word:
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']
words[-1] = '"' words[-1] '"'
line = ' '.join(words)
# print(line) # vlan xxx name "xxx"
fout.write(line)
WARNING: in your question, you say you'd like the output to be vlan xxx name "xxx" which has two spaces after the first xxx. This result would only have one space between each word.
