如何计算文件中的所有行,单词和字符

时间:2015-11-05 21:29:51

标签: python file

我试图编写一个计算.txt文件中所有行,单词和字符的程序。我有线出来,但我不知道怎么做单词或字符。

"""Write a function stats() that takes one input argument: the name of a text file. 
   The function should print, on the screen, the number of lines, words, 
   and characters in the file; your function should open the file only once. 
   stats( 'example.txt') line count: 3 word count: 20 character count: 98"""

def stats(inF):

    inFile=open(inF,'r')  
    text=inFile.readlines() 
    textLen=len(text)  
    print(textLen) 

    wordCount=0
    charCount=0

    for word in inFile.read().split():
        if word in inFile:
            wordCount = + 1
        else:
            wordCount = 1
    print(wordCount)

print(stats("n.txt")) 

2 个答案:

答案 0 :(得分:1)

每当你在python中进行文件I / O时,我都会建议使用withdocs)。此外,迭代每一行而不是使用inFile.read()。如果您有一个大文件,您的机器内存将感谢您。

def stats(inF):

    num_lines = 0
    num_words = 0
    num_chars = 0

    with open(inF, 'r') as input_file:
        for line in input_file:
            num_lines += 1
            line_words = line.split()
            num_words += len(line_words)
            for word in line_words:
                num_chars += len(word)

    print  'line count: %i, word count: %i, character count: %i' % (num_lines, num_words, num_chars)


stats('test.txt')

答案 1 :(得分:0)

我会指出你正确的方向,而不是最好的python编码器,但这就是你想要在逻辑上解决它的方式。这也是考虑到你不想数“或”。作为人物。

inFile=open(inF,'r')  

for line in inFiler:
    linecount++

    #use a tokenizer to find words
    newWord = true
    for character in line:

        #something like this
        if newWord:
            if character is not listOfNoneValidCharacters(" ", ".", ...etc):
                newWord = false
                charCount += 1
                wordCount += 1

        if not newWord:
            if character is not listOfNoneValidCharacters:
                charCount += 1
            newWord = true