【问题标题】:Python search/replaice with readline and if elsePython 搜索/替换为 readline 和 if else
【发布时间】:2014-01-13 12:26:30
【问题描述】:

我正在编写一个简单的 python 脚本,它解析一个文本文件并正在寻找一个字符串,如果找到该字符串,则将用另一个字符串替换该字符串,如果未找到该搜索字符串,则附加一个字符串。

我想要一些类似的东西:

#!/usr/bin/python2
import fileinput, glob, string, sys, os 
from os.path import join

myfile="textfile.txt"

search_string="pussy"
replace_string1="tutti"
replace_string2="frutti"

replace_strings = replace_string1 + '\n' + replace_string2

stext = str(search_string);
rtext = str(replace_strings);

print "finding:\n" + stext + "\n\nreplacing with:\n" + rtext + "\n\nin:\n" + myfile

for line in fileinput.input(myfile,inplace=1):
   lineno = 0 
   lineno = string.find(line, stext)
if lineno >=0:
    line = line.replace(stext, rtext)
    sys.stdout.write(line)
else:
    print "append line"

所以如果我使用这个脚本将运行 if 语句和 else!怎么了?

【问题讨论】:

  • 发布Python问题时需要使用正确的缩进;您的 if lineno >= 0 测试甚至不是 fileinput.input() 循环的一部分,它前面的行使用 3 个空格而不是 4 个,但后面的行 do 使用 4。所有这些都使您的代码无效。跨度>
  • 你想用lineno 变量做什么? lineno总是会是0,所以lineno >= 0总是正确的。
  • 是否要将文本附加到文件末尾,并且仅在未找到搜索文本时才添加?应该替换所有个搜索文本,还是只替换第一个?

标签: python string search file-io replace


【解决方案1】:

缩进在 Python 中非常重要。比较您的代码:

for line in fileinput.input(myfile,inplace=1):
   lineno = 0 
   lineno = string.find(line, stext)
if lineno >=0:
   line = line.replace(stext, rtext)
    sys.stdout.write(line)
else:
    print "append line"

使用这个版本:

for line in fileinput.input(myfile,inplace=1):
    lineno = 0 
    lineno = string.find(line, stext)
    if lineno >=0:
        line = line.replace(stext, rtext)
        sys.stdout.write(line)
    else:
        print "append line"

看到区别了吗? 你的 if 在 for 循环结束后执行,lineno 包含它的最后一次评估(显然,你的 stext 不包含在文件的最后一行......,这就是它的全部含义)。

【讨论】:

  • 代码仍然无法正常工作,因为它会为输入中与搜索文本不匹配的任何行打印append line。缩进不是问题的原因,只是一个不知道如何在 SO 上发布的工件。
  • @Martijn Pieters 他希望代码为输入中与搜索文本不匹配的任何行输出append line
  • 我不太确定。 OP 写道:如果我使用它,该脚本将运行 if 语句和 else!,这意味着他很惊讶append line 打印即使有匹配也会发生。
  • 我没有这样解释。目标是替换与stext 匹配的行并附加(即,保持原样)其他行。我将打印append line 解释为某种控制,意思是“这条线没问题,它不包含stext,所以我就追加它”
  • 啊,OP 现在表明我的代码实际上做了他想做的事情。
【解决方案2】:

您无法轻松地将行附加到带有fileinput.input() 的文件末尾,因为您无法在没有找到匹配项的情况下轻松检测文件何时结束。您还使用了string.find(),这不是测试文本是否存在的最佳方法,因为当找不到文本时返回-1,您没有正确测试。

循环完fileinput.input()后,您必须以附加模式重新打开文件:

import fileinput
import sys

myfile = "textfile.txt"

search_string = "pussy"
replace_string = "tutti\nfrutti"

found = False 
for line in fileinput.input(myfile, inplace=1):
    if search_string in line:
        found = True
    line = line.replace(search_string, replace_string)
    sys.stdout.write(line)

if not found:
    with open(myfile, 'a') as outfh:
        outfh.write(replace_string + '\n')

【讨论】:

  • 请注意,您似乎已经接受 Marcos 的回答是正确的,但您在这里的评论似乎暗示他对您的缩进的更正不是您想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 2014-11-29
  • 2015-09-25
  • 2014-06-16
相关资源
最近更新 更多