【问题标题】:insert a new line to a file if findall finds a search pattern如果 findall 找到搜索模式,则在文件中插入新行
【发布时间】:2018-12-10 07:56:21
【问题描述】:

我想在findall 找到搜索模式后向文件添加新行。我使用的代码只将输入文件的内容写入输出文件。它不会在输出文件中添加新行。如何修复我的代码?

import re
text = """
Hi! How are you?
Can you hear me?
"""
with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for line in readcontent:
    x1 = re.findall(text, line)
    if line == x1:
        line = line + text
    out_file.write(line)

输入.txt:

ricochet robots
settlers of catan
acquire
Hi! How are you?
Can you hear me?
this is very valuable
finish

所需的输出.txt:

ricochet robots
settlers of catan
acquire
Hi! How are you?
Can you hear me?

Added new line

this is very valuable
finish

【问题讨论】:

  • 基本上,您需要在每个“你能听到我的声音吗?”之后换行。 ?
  • 只有一行“你能听到我说话吗?”在输入文件中。所以在那之后我只需要一个新行。
  • 一行或多行,regex 在这里似乎有点矫枉过正。
  • @klutt 实际输出类似于所需的输出。正如我之前所说,我需要使用findall 在输入文件中查找多行。实际输入更复杂。

标签: python regex python-3.x python-2.7 findall


【解决方案1】:

这里不要使用regex。检查当前行,如果是要检查的行,则添加一个换行符。

with open("output.txt", "w") as out_file:
    for line in readcontent:
        out_file.write(line)
        if line.strip() == 'Can you hear me?':
            out_file.write('\n')

如果您需要 regex 本身,请选择以下内容(尽管我绝不会推荐):

with open("output.txt", "w") as out_file:
    for line in readcontent:
        out_file.write(line)
        if re.match('Can you hear me?', line.strip()):
            out_file.write('\n')

【讨论】:

  • 请注意,我需要使用findall
  • @erhan 这里不适合使用findall
【解决方案2】:

尝试遍历每一行并检查您的文本是否存在。

例如:

res = []
with open(filename, "r") as infile:
    for line in infile:
        if line.strip() == "Hi! How are you?":
            res.append(line.strip())
            lineVal = (next(infile)).strip() 
            if lineVal == "Can you hear me?":
                res.append(lineVal)
                res.append("\n Added new line \n")
        else:
            res.append(line.strip())



with open(filename1, "w") as out_file:
    for line in res:
        out_file.write(line+"\n")

输出:

ricochet robots
settlers of catan
acquire
Hi! How are you?
Can you hear me?

 Added new line 

this is very valuable
finish

【讨论】:

  • 我需要使用 findall 但你的代码没有使用它。
  • 这是一个没有正则表达式的解决方案。
【解决方案3】:

这是你想要的吗:

text = "Can you hear me?"
with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for idx,line in enumerate(readcontent):
       if line.rstrip() == text:
           line+='\nAdded new line\n\n'
       out_file.write(line)

output.txt 看起来像:

ricochet robots
settlers of catan
acquire
Hi! How are you?
Can you hear me?

Added new line

this is very valuable
finish

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2016-05-18
    • 2014-09-13
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多