Find the number of characters in a file using Python

后端 未结 16 1482
春和景丽
春和景丽 2021-02-07 00:34

Here is the question:

I have a file with these words:

hey how are you
I am fine and you
Yes I am fine

And it is asked to find the numbe

相关标签:
16条回答
  • 2021-02-07 01:12

    It's very simple:

    f = open('file.txt', 'rb')
    f.seek(0) # Move to the start of file
    print len(f.read()) 
    
    0 讨论(0)
  • 2021-02-07 01:12

    taking the input as file name i.e files.txt from the input parameter and then counting the total number of characters in the file and save to the variable char

    fname = input("Enter the name of the file:")
    infile = open(fname, 'r')                   # connection of the file
    lines = 0
    words = 0
    char = 0                                    # init as zero integer
    for line in infile:
        wordslist = line.split()                # splitting line to word
        lines = lines + 1                       # counter up the word
        words = words + len(wordslist)          # splitting word to charac
        char = char + len(line)                 # counter up the character
    
    print("lines are: " + str(lines))
    print("words are: " + str(words))
    print("chars are: " + str(char))            # printing beautify
    
    0 讨论(0)
  • 2021-02-07 01:16

    Simply skip unwanted characters while calling len,

    import os
    characters=characters+ len([c for c in line if c not in (os.linesep, ' ')])
    

    or sum the count,

    characters=characters+ sum(1 for c in line if c not in (os.linesep, ' '))
    

    or build a str from the wordlist and take len,

    characters=characters+ len(''.join(wordlist))
    

    or sum the characters in the wordlist. I think this is the fastest.

    characters=characters+ sum(1 for word in wordlist for char in word)
    
    0 讨论(0)
  • 2021-02-07 01:18

    You have two problems. One is the line endings and the other is the spaces in between.

    Now there are many people who posted pretty good answers, but I find this method easier to understand:

    characters = characters + len(line.strip()) - line.strip().count(' ')
    

    line.strip() removes the trailing and leading spaces. Then I'm subtracting the number of spaces from the total length.

    0 讨论(0)
  • 2021-02-07 01:20

    You do have the correct answer - and your code is completely correct. The thing that I think it is doing is that there is an end of line character being passed through, which includes your character count by two (there isn't one on the last line, as there is no new line to go to). If you want to remove this, the simple fudge would be to do as Loaf suggested

    characters = characters - (lines - 1)
    

    See csl's answer for the second part...

    0 讨论(0)
  • 2021-02-07 01:20

    Here i got smallest program with less memory usage for your problem

    with open('FileName.txt') as f:
      lines = f.readlines()
      data = ''.join(lines)
      print('lines =',len(lines))
      print('Words = ',len(data.split()))
      data = ''.join(data.split())
      print('characters = ',len(data))
    

    lines will be list of lines,so length of lines is nothing but number of lines.Next step data contains a string of your file contents(each word separated by a whitespace), so if we split data gives list of words in your file. thus, length of that list gives number of words. again if we join the words list you will get all characters as a single string. thus length of that gives number of characters.

    0 讨论(0)
提交回复
热议问题