替换文档中的单词

时间:2013-12-22 01:34:54

标签: python

我的目标是编写一个带两个字符串和两个文件名的函数。该函数用第二个字符串替换第一个文件中的第一个字符串。之后,它将内容写入第二个文件。这就是我所做的:

def sed(s1, s2, f1, f2):
    try:
        fin1 = open(f1,'r')
        fin2 = open(f2, 'w')
        for word in fin1:
            if word == s1:
                word = s2
                fin2.write(word)
            else:
                fin2.write(word)
    except:
        'something went wrong'

然而,替换部分并不是很有效。第一个字符串没有被第二个字符串替换。我知道有一个用Python构建的.replace,但我想为练习编写自己的替换函数。

2 个答案:

答案 0 :(得分:1)

要从行中获取单词,请使用str.split()

for line in fin1:
    for word in line.split():

答案 1 :(得分:-1)

对于像这样的任务不使用内置方法不是一个好主意,因为你使事情变得很复杂。我假设您不想使用正则表达式操作模块'重新'...​​所以在下面找到我的答案。这可以用更少的行编写,但这种方式更具可读性:

def replace_string(string1, string2, file1, file2):
  with open(file1, 'r') as first_file:
    my_lines = []
    for line in first_file.readlines():
      if string1 in line:
        for word in line.split(string1):
          if word != string1:
            if (word and '\n' not in word):
              new_word = word+string2
            else:
              new_word = word
          my_lines.append(new_word)
      else:
        my_lines.append(line)
  with open(file2, 'w') as second_file:
    for item in my_lines:
      second_file.write(item)

假设您有'first_file.txt',如下所示:

This is my first line. It contains the words: cat, dog, fish, cat.
This is the second line. cat. ‘cat’ is a pet
This is the third line. cat...cat cat.
You have hopefully replaced all occurrences of *cat*cat

并且您希望将字符串'cat'替换为'new_cat'并将其保存到文件'second_file.txt'。您不需要创建second_file.txt,它只会在您运行代码的相同位置创建。

replace_string('cat', 'new_cat', 'first_file.txt', 'second_file.txt')

您的第二个文件将如下所示:

This is my first line. It contains the words: new_cat, dog, fish, new_cat.
This is the second line. new_cat. ‘new_cat’ is a pet
This is the third line. new_cat...new_cat new_cat.
You have hopefully replaced all occurrences of *new_cat*new_cat

当然,这并不完美。如果你的文件'catcat'中有一个单词,会发生什么......你想忽略它吗?或者你想把它变成'new_catnew_cat'?这段代码只会把它变成'new_cat'......所以这里有另一个要检查的条件等等......