如何计算fi中的所有行、单词和字符

2024-05-21 23:44:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个程序来计算.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")) 

Tags: ofthetextinletxtstatscount
2条回答

每当您用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')

我会给你指出一个正确的方向,不是最好的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

相关问题 更多 >