Find and replace string between quotes

老子叫甜甜 提交于 2020-01-30 02:33:11

问题


I'm reading a file and I would like to replace any text which appears between two double quotes like this:

If file input is:

Hi, I'm an example file! "Hi there example file."

"I'm mostly just here to get this quote to be colored!"

Output should be:

Hi, I'm an example file! [color=x]"Hi there example file."[/color]

[color=x]"I'm mostly just here to get this quote to be colored!"[/color]


I've wrote these three modules to do that, the first two work but the last doesn't.

Module 1:

__author__ = 'Joker'
import os
import sys
import re
import fileinput

print ("Text to search for:")
textToSearch = ( '" ' )

print ("Text to replace it with:")
textToReplace = ( '"[/color] ' )

print ("File to perform Search-Replace on:")
fileToSearch  = ( "D:\Coding projects\post edit\post.txt" )


tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()

input( '\n\n Press Enter to exit...' )

Module 2:

__author__ = 'Joker'
import os
import sys
import re
import fileinput

print ("Text to search for:")
textToSearch = ( ' "' )

print ("Text to replace it with:")
textToReplace = ( ' [color=#66ccff]"' )

print ("File to perform Search-Replace on:")
fileToSearch  = ( "D:\Coding projects\post edit\post.txt" )

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()

input( '\n\n Press Enter to exit...' )

Module 3:

__author__ = 'Joker'
import os
import sys
import re
import fileinput

print ("Text to search for:")
textToSearch = ( r'\n"')

print ("Text to replace it with:")
textToReplace = (r'\n[color=#66ccff]"' )

print ("File to perform Search-Replace on:")
fileToSearch  = ( "D:\Coding projects\post edit\post.txt" )

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()

input( '\n\n Press Enter to exit...' )

Bonus: is there a way to combine the functionality of these three modules into one?


回答1:


Try using re the regular expression module for that:

import re 

text = open(filename).read()  # read the entire file content

# define your tags here
opening_tag = '[color=x]'
closing_tag = '[/color]'

matches = re.findall(r'\"(.+?)\"',text)  # match text between two quotes
for m in matches:
  text = text.replace('\"%s\"' % m, '%s\"%s\"%s' % (opening_tag, m, closing_tag))  # override text to include tags

# write modified text with tags to file
with open(filename, 'w') as f:
  f.write(text)

#  for the input you specified, the new file should be:
>> [color=x]"Hi there example file."[/color]
>> [color=x]"I'm mostly just here to get this quote to be colored!"[/color]



回答2:


Ended up using @Forge's answer as an inspiration. So major credits to him. However this is how I ended up fixing it. Including the final outcome:

import re 

string = open('post.txt').read()  # read the entire file content
cfile = open('character.txt').read() #Read character

#select a color
variable=raw_input('which character are you using?\n')
print variable
ini=cfile.find(variable)+(len(variable)+1)
rest=cfile[ini:]
search_enter=rest.find('\n')
color=str(rest[:search_enter])

# define your tags here
opening_tag = '[color=%s]' % (color)
closing_tag = '[/color]'

matches = re.findall(r'\"(.+?)\"',string)  # match text between two quotes
for m in matches:
    string = string.replace('\"%s\"' % (m), '\"%s%s%s\"' % (opening_tag, m, closing_tag))  # override text to include tags

print string

# write tagged text to file
with open('post.txt', 'w') as f:
  f.write(string)


来源:https://stackoverflow.com/questions/35811624/find-and-replace-string-between-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!