【问题标题】:python counting charaters without spaces in a filepython计算文件中没有空格的字符
【发布时间】:2017-04-15 14:24:37
【问题描述】:

你如何计算没有空格的字符?我没有得到正确的号码。 num_charsx 的正确数是 1761

num_words = 0
num_chars = 0
with open("C:/Python33/fire.txt",'r') as f:
   for line in f:
       words = line.split('\n')
       num_words += len(words)
       num_chars += len(line)
   num_charsx = num_chars - line.count(' ')
print(num_charsx)
2064

【问题讨论】:

    标签: python file character


    【解决方案1】:
    words = line.split('\n')
    num_words += len(words)
    

    没有做你认为它做的事。在循环中

    for line in f:
    

    line 是一个以'\n' 结尾的字符串,所以line.split('\n') 是一个包含两项的列表,其中第一项包含该行的所有字符,除了终止符'\n';该列表中的第二项是空字符串。示例:

    line = 'This is a test\n'
    words = line.split('\n')
    print(words, len(words))
    

    输出

    ['This is a test', ''] 2
    

    所以你的 num_words += len(words) 实际上并没有计算字数,它只是计算行数的两倍。

    要获得line 中单词的实际列表,您需要

    words = line.split()
    

    你的倒数第二行

    num_charsx = num_chars - line.count(' ')
    

    for 循环之外,因此它会从num_chars 总数中减去文件最后一行的空间数,但我假设您确实想从num_chars 中减去整个文件的总空间数.

    这是您的代码的修复版本。

    num_words = 0
    num_chars = 0
    num_spaces = 0
    with open(fname, 'r') as f:
       for num_lines, line in enumerate(f, 1):
           num_words += len(line.split())
           num_chars += len(line) - 1
           num_spaces += line.count(' ')
    
    num_charsx = num_chars - num_spaces
    print(num_lines, num_words, num_chars, num_spaces, num_charsx)
    

    我已将行阅读循环修改为使用enumerate。这是获取行号和行内容的有效方法,无需维护单独的行计数器。

    num_chars += len(line) - 1 中,-1 是所以我们不将每行的终止'\n' 包括在字符数中。

    请注意,在 Windows 上,文本文件行(通常)以 '\r\n' 终止,但当您读取以文本模式打开的文件时,该终止符会转换为 '\n'。所以在 Windows 上文件的实际字节大小是num_chars + 2 * num_lines,假设最后一行有一个'\r\n' 终止符;它可能不会,在这种情况下,实际大小将比这小 2 个字节。

    【讨论】:

      【解决方案2】:

      您可能想尝试使用 ' ' 而不是 '\n' 来分割行。因为 '\n' 应该由 for 循环完成。

      如果你只想要一个字符计数,另一个选择是你可以使用 replace 方法删除 ' ' 然后计算字符串的长度。

      num_chars = len(line.replace(' ', ''))
      

      【讨论】:

        【解决方案3】:

        你也可以试试这个:

        num_chars = 0
        with open("C:/Python33/fire.txt",'r') as f:
            for line in f:
                num_chars += len(line.split('\n')[0])
            num_charsx = num_chars - line.count(' ')
        print(num_charsx)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-30
          • 1970-01-01
          • 1970-01-01
          • 2020-09-14
          • 1970-01-01
          相关资源
          最近更新 更多