Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换文档中的单词_Python - Fatal编程技术网

Python 替换文档中的单词

Python 替换文档中的单词,python,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

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

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,但我想编写自己的replace函数以供练习。

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


对于这样的任务,不使用内置方法不是一个好主意,因为这样会使事情变得非常复杂。我假设您也不想使用正则表达式操作模块're',那么请在下面找到我的答案。这可以用更少的行来书写,但这种方式更具可读性:

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
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
您希望将字符串“cat”替换为“new_cat”,并将其保存到文件“second_file.txt”中。您不需要创建第二个_file.txt,它将在运行代码的同一位置创建

replace_string('cat', 'new_cat', 'first_file.txt', 'second_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
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_cat”…因此这里有另一个要检查的条件,等等…

对于fin1中的word:
逐行读取文件,而不是逐字读取。我如何使其逐字读取?我可以推荐
而不是您所拥有的,除非异常为e:sys.exit(“出错时的某物:+str(e))
。通过这种方式,你可以确切地看到出了什么问题。在实践中,您应该捕获特定的错误,如
OSError
IOError
,这样其他意外错误,如
AttributeError
TypeError
不会神秘地让您陷入白费力气的追逐。此外,只需输入字符串
“出错了”
也不会有任何作用。您需要打印
系统退出
,这取决于您的意图。将您的代码包装在一个包罗万象的
try except
块中通常是一个非常糟糕的主意(是的,该规则有……嗯……例外)。一个问题是,默认情况下,它将在空白处拆分,单词将包括尾随逗号和句号。这也是正确的,但出于这个原因,它仍然值得一提