【问题标题】:Copy string from file to file until one character is found in Python将字符串从一个文件复制到另一个文件,直到在 Python 中找到一个字符
【发布时间】:2023-01-16 16:10:46
【问题描述】:

我有两个文本文件。我想阅读文本 1 并查找字符串“example”,当找到这个字符串时,我想将它与下一个字符一起复制,直到找到字符“A”。例如: text1.txt 中的内容:“jnajsndneuinnuincuiewexampleohelloAhyhakjs” text2.txt 中复制的内容:“ejemplohello” 问题是 text1 会不断增长,我必须循环执行此任务,因此,另一个限制是第二次出现“example”时,我必须在它之后保存第二个字符串,而不是第一个(“hello”) .例子:

text1.txt中的内容:

"jnajsndneuinnuincuiewexampleohelloAhyhakjsexamplegoodbyeAhjuheui"

text2.txt中复制的内容:

"ejemplohelloexamplegoodbye"

知道如何在 Python 中执行此操作吗?

我已经尝试过这段代码,但它无法正常工作,而且一旦找到该字符串一次,它就无法正常工作:

def detect(k):
   string = "example"
   with open("tex1.txt", "r") as f:
      content = f.read()
      if string in content:
         with open("text2.txt", "a+") as f:
            if (character != "A"): 
               f.write(k)

【问题讨论】:

    标签: python string loops search


    【解决方案1】:

    以下是如何在 Python 中完成此任务的示例:

    def detect_and_copy(file1, file2):
        string = "example"
        with open(file1, "r") as f1:
            content = f1.read()
            idx = content.find(string)
            while idx != -1:
                next_idx = content.find("A", idx)
                if next_idx == -1:
                    next_idx = len(content)
                with open(file2, "a+") as f2:
                    f2.write(content[idx:next_idx])
                idx = content.find(string, idx+1)
    

    此函数将两个文件名作为输入(file1 和 file2),并以读取模式打开 file1,以追加模式打开 file2。然后它使用 find() 方法在 file1 的内容中查找字符串“example”。如果找到该字符串,它会使用 find() 方法查找字符“A”的下一次出现。如果未找到该字符,它将 next_idx 设置为内容的长度。然后它使用 write() 方法将“example”索引到“A”索引(或内容结尾)的子字符串写入 file2。重复此过程,直到找到并处理“example”的所有实例。

    你可以像这样调用这个函数:

    detect_and_copy("text1.txt", "text2.txt")
    

    请注意,上述解决方案会将数据附加到 text2.txt。如果你想每次调用函数都覆盖它,你应该使用'w'模式而不是'a+'模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多