【问题标题】:Python : Given a text file with space delimited, How to count to number of columns in each row or line of text filePython:给定一个以空格分隔的文本文件,如何计算文本文件每行或每行中的列数
【发布时间】:2016-02-28 20:51:04
【问题描述】:

有没有其他方法可以找到每行文本文件中的列数。

with open(path, 'r') as f:
        for line in f:
            columns    = line.strip().split()
            print(len(columns), 'columns')

【问题讨论】:

    标签: string python-3.x text whitespace string-length


    【解决方案1】:

    简单地说:line.count(' ') 没有。空间? + 1 没有。列数?

    以及反汇编程序的故障:

    >>> import dis
    >>> line = "1 2 3 4\n"
    >>> m1 = lambda x: line.count(' ')
    >>> m2 = lambda x: len(line.split()) 
    >>> dis.dis(m1)
      1           0 LOAD_FAST                0 (x)
                  3 LOAD_ATTR                0 (count)
                  6 LOAD_CONST               1 (' ')
                  9 CALL_FUNCTION            1
                 12 RETURN_VALUE        
    >>> dis.dis(m2)
      1           0 LOAD_GLOBAL              0 (len)
                  3 LOAD_FAST                0 (x)
                  6 LOAD_ATTR                1 (split)
                  9 CALL_FUNCTION            0
                 12 CALL_FUNCTION            1
                 15 RETURN_VALUE  
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多