-1

我不知道如何解决这个问题,我试图在一个包含大量空格和特殊字符的文本文件中匹配这个长字符串,并将这些字符附加到前面,即。"//"

我需要匹配这一行:

$menu_items['gojo_project']                    => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),

并将其变成这样:

//$menu_items['gojo_project']                    => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),

请注意,我只是在前面添加了两个“/”字符。

我尝试使用 re.escape 格式化字符串,但它真的很长并且仍然抛出语法错误。我是否以正确的方式使用're'?还是有更好的pythonic方法来匹配文本文件中这样的字符串并添加到它前面?

编辑:忘了提到我需要在线编辑文件。简而言之,它是一个很长的 php 脚本,我试图找到该行并将其注释掉(即。//)。所以,我不能真正使用一些建议的解决方案(我认为),因为他们已经将修改写入单独的文件。

4

2 回答 2

2

试试fileinput它会让你读取文件并在适当的位置重写行:

import fileinput

for line in fileinput.input("myfile.txt", inplace = 1):
    if line == "$menu_items['gojo_project']                    => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),":
        line = '//' + line
    print line,
于 2012-02-23T16:03:42.507 回答
0

如果您尝试完全匹配该字符串,则使用字符串相等运算符而不是正则表达式会更容易。

longString = "$menu_items['gojo_project']                    => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),"

input = open("myTextFile.txt", "r")
output = open("myOutput.txt", "w")
for line in input:
    if line.rstrip() == longString: #rstrip removes the trailing newline/carriage return
        line = "//" + line
    output.write(line)
input.close()
output.close()
于 2012-02-23T16:03:13.807 回答