需要从Python中删除特定行中的特定单词

时间:2015-04-03 08:22:28

标签: python python-2.7

我的文本文件是这样的:

“彩虹有七种颜色。

降雨过后,彩虹升起。“

我希望从第一行删除“rainbow”这个词,而不是从第二行和新文件中删除所有要打印的行,因为它在第一行没有彩虹。使用这样的代码:

infile = "old.txt"
outfile = "new.txt"

delete_word = ["rainbow"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
      for word in delete_word:
            if 'has' in line:
                line = line.replace(word, "")
                fout.write(line)
fin.close()
fout.close()

我只获得没有'彩虹'的第一行。

2 个答案:

答案 0 :(得分:2)

infile = "old.txt"
outfile = "new.txt"

delete_word = "rainbow"
with open(infile, "r") as fin, open(outfile, "a") as fout:
    for line in fin:
        for word == delete_word:
            line = line.replace(word, "")
        fout.write(line)

答案 1 :(得分:1)

尝试:

infile = "old.txt"
outfile = "new.txt"

delete_word = ["rainbow"]
lines = [1] #List of lines you want to delete the word from
fin = open(infile)
fout = open(outfile, "w+")
line_count = 0
for line in fin:
      line_count += 1
      for word in line.split():
            if word in delete_word and line_count in lines:
                line = line.replace(word, "")
      fout.write(line)
fin.close()
fout.close()