【问题标题】:Find and replace string between quotes查找和替换引号之间的字符串
【发布时间】:2016-03-05 07:56:42
【问题描述】:

我正在读取一个文件,我想替换出现在两个双引号之间的任何文本,如下所示:

如果文件输入是:

嗨,我是一个示例文件! “你好,示例文件。”

“我主要是为了给这句话涂上颜色!”

输出应该是:

嗨,我是一个示例文件! [color=x]“你好,示例文件。”[/color]

[color=x]“我主要是为了给这句话涂上颜色!”[/color]


为此,我编写了这三个模块,前两个有效,但最后一个无效。

模块 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...' )

模块 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...' )

模块 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...' )

奖励:有没有办法将这三个模块的功能合二为一?

【问题讨论】:

  • 我已经在里面输入了。添加了输出。感谢您的提醒(我确实阅读了如何提问部分。)

标签: python regex file-io


【解决方案1】:

尝试为此使用re regular expression 模块:

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]

【讨论】:

  • 回溯(最近一次调用最后一次):第 15 行,在 f.write() 类型错误:函数只需要 1 个参数(给定 0)给我一个错误,挠头想明白出来。
  • 更新答案@TheJoker。
  • 错误已修复,但是在运行代码后,我的文件中的任何对话都没有被新格式替换。 当前代码: link 运行后的post.txt: link - 文件已更改(因为notepad++要求重新加载它。)但没有任何内容被更改.
  • 我发现了问题。我只是不知道解决方案: 在 text.replace 我认为: '\"%s\"' % m - 不允许脚本识别我们希望它用引号替换引号内的文本,内边的文本被包围我们的标签。
【解决方案2】:

最终以@Forge 的回答为灵感。所以主要归功于他。然而,这就是我最终修复它的方式。包括最终结果:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2015-09-03
    相关资源
    最近更新 更多