【问题标题】:How to add something to a lot of line from a file until condition is met?如何在满足条件之前从文件中添加很多内容?
【发布时间】:2018-02-26 06:34:28
【问题描述】:

所以我有一个如下所示的文本文件:

'''

姓名:约翰

姓:布朗

'''

我只想在 ''' 引号的开头和所有行的开头打印一些内容,直到我读到另一组引号。

这是我一直在尝试编写的代码:

for line in infile:
    if line.find("'''") !=-1:        
            print("PROTECTED",line.rstrip(),end = "")

我希望它是什么样子:

受保护的'''

受保护的姓名:约翰

受保护的姓氏:布朗

受保护的'''

在那之后我有更多数据,但我不知道如何只将 PROTECTED 放在这些行上。

我认为我的 for 循环有点错误,我需要帮助。

【问题讨论】:

    标签: python file for-loop if-statement printing


    【解决方案1】:

    添加一个标签来表明你是否找到了第一个''',如果你找到了,然后设置标签并为之后的所有行添加“PROTECTED”,直到你找到另一个'''。下面是代码示例:

    firstPosFound = False
    
    for line in infile:
        if line.find("'''") !=-1 and firstPosFound == False:
            print("PROTECTED",line.rstrip(),end = "")
            firstPosFound = True
            continue
    
        if line.find("'''") !=-1 and firstPosFound == True:
            print("PROTECTED",line.rstrip(),end = "")
            firstPosFound = False
            continue
    
        if firstPosFound == True:
            print("PROTECTED", line.rstrip(), end="")
    

    【讨论】:

      【解决方案2】:

      您不必使用line.find 来检查一个字符串是否包含另一个字符串,python 让这很容易:

      if "'''" in line:

      只要'''单独在一行上,你就可以检查该行是否等于''',然后切换一个布尔值在每行之前打印PROTECTED

      intext = """other text
      '''
      Name: John
      Last Name: Brown
      '''
      some other text"""
      
      protec = False
      for line in intext.split("\n"):
          if "'''" == line: #on a line which has triple quotations
              protec = not protec #toggle boolean
              print("PROTECTED", line.rstrip())
          else: 
              if protec: #if text is between '''
                  print("PROTECTED", line.rstrip())
      

      输出:

      受保护的'''

      受保护的姓名:约翰

      受保护姓氏:布朗

      受保护的'''

      【讨论】:

      • 我尝试了类似的方法,但出现错误我无法真正理解该错误:def main(): file = open("data.py","r") infile = file.readlines () protec = False for line infile.split("\n"): if "'''" == line: #在有三引号的行上 protec = not protec #toggle boolean print("PROTECTED", line .rstrip()) else: if protec: #if text is between ''' print("PROTECTED", line.rstrip()) main()
      • 没关系,我想通了!!谢谢你的例子!非常感谢。
      【解决方案3】:

      一种方法是使用标志变量:

      inside_quotes = False
      for line in infile:
          if (line.find("'''") !=-1):
              print("PROTECTED",line.rstrip(),end = "")
              inside_quotes = not inside_quotes
              continue
          if inside_quotes:
              print("PROTECTED",line.rstrip(),end = "")
      

      可能还有更好的方法,这只是我想到的第一个方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-29
        • 2019-11-11
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2016-05-30
        相关资源
        最近更新 更多