【问题标题】:How can I detect the first non-whitespace character in each line of a file opened in Python?如何检测在 Python 中打开的文件的每一行中的第一个非空白字符?
【发布时间】:2021-05-28 05:20:39
【问题描述】:

我正在尝试编写 Python 代码来检测文件中每一行中的第一个非空白字符并检查它是否是“}”。例如,如果我的文件内容是...

a
fox {
  }
{ jumped
} up

...我想检测第三行中的“}”,尽管它有两个空格,并且在第五行中。

我试过做这样的事情,但我卡住了:

full_file = open ("filename", "r")
each_line = full_file.readlines()
for item in each_line
  if item[0].find('}') != -1:
    # do something, such as print (item)
full_file.close()

非常感谢您的帮助!

【问题讨论】:

    标签: python special-characters


    【解决方案1】:

    您可以尝试在每一行调用strip(),然后只检查第一个字符:

    full_file = open ("filename", "r")
    each_line = full_file.readlines()
    for item in each_line
        if item.strip() and item.strip()[0] == '}':
            print(item)
    full_file.close()
    

    【讨论】:

    • 我更喜欢item.strip().startswith('}'),以防strip()之后的行为空。
    • 效果很好。作为问题的扩展,假设我想检测“}”之后的下两个字符,其中第一个字符是空格。像这样:a fox { } \ { jumped } up 我只想检测第三行中的字符。不优雅的解决方案是嵌套两个 if 语句,但有没有更聪明的方法可以使用切片来做到这一点?
    • 只需使用item.strip()[0:2],即可获取由前3个字符组成的子字符串(删除初始空格后)。
    • 喜欢这个? if item.strip() and item.strip()[0:2] == "} \\"
    • @TimBiegeleisen,如果我不转义反斜杠,解释器会产生语法错误:扫描字符串文字时 EOL。
    【解决方案2】:

    您可以使用此函数获取第一个非空白字符。

    这一次只读取一行,因此如果您正在处理一个非常大的文件,它可以为您节省一些麻烦。

    def get_first_non_whitespace_char(file_name):
        with open(file_name, 'r') as fileobj:
            for line in fileobj:  
                for character in line:
                    if character != " ":
                        return character
        return None
    

    尝试使用这样的文件:

    sample.txt

         }hello
    

    使用函数

    file_name = "sample.txt"
    
    first_nsp_char = get_first_non_whitespace_char(file_name)
    
    if first_nsp_char != None:
        print("First Non space character in file:", first_nsp_char)
        print("Character is '}' :", first_nsp_char == '}')
    else:
        print("No non-whitespace characters found in file:", file_name)
    

    输出:

    First Non space character in file: }
    Character is '}' : True
    

    【讨论】:

      【解决方案3】:

      我的版本略有不同的输入(sample.txt 末尾有两个空行,'\n'):

      a
      fox {
        }
      { jumped
      
      
      } up
      
      
      
      
      

      是:

      #!/usr/bin/env python3
      # -*- coding: utf-8 -*-
      """
      Created on Thu Jun 10 11:28:29 2021
      
      @author: Pietro
      
      https://stackoverflow.com/questions/67733277/how-can-i-detect-the-first-non-whitespace-character-in-each-line-of-a-file-opene/67733429#67733429
      
      """
      
      def get_first_non_whitespace_char(file_name):
          listz ={}
          index = 0
          with open(file_name, 'r') as fileobj:
              for line in fileobj:
                  index += 1
                  #print('line: ',line)
                  for character in line:
                      if character != " " and character != '\n':
                          listz[index] = character
                          # index += 1
                          break
                      else:
                          pass
          return listz
      
      
      file_name = "sample.txt"
      
      first_nsp_char = get_first_non_whitespace_char(file_name)
      
      for i in first_nsp_char:
            print('line # ',i,'  first character is : ',first_nsp_char[i])
      

      输出:

      line #  1   first character is :  a
      line #  2   first character is :  f
      line #  3   first character is :  }
      line #  4   first character is :  {
      line #  7   first character is :  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-12
        • 1970-01-01
        • 2018-03-04
        • 2017-09-21
        • 2011-01-23
        • 2014-10-26
        • 1970-01-01
        相关资源
        最近更新 更多