使用Python打印字符,单词和行数

时间:2015-10-03 21:58:07

标签: python file character line word

这是我到目前为止所做的:

def stats(filename):
    ' prints the number of lines, words, and characters in file filename'
    infile = open(filename)
    lines = infile.readlines()
    words = infile.read()
    chars = infile.read()
    infile.close()
    print("line count:", len(lines))
    print("word count:", len(words.split()))
    print("character counter:", len(chars))

执行时,正确返回行数,但对单词和字符计数返回0。不知道为什么......

4 个答案:

答案 0 :(得分:3)

你可以迭代文件一次并计算行,单词和字符,而不需要多次回到开头,这需要你的方法,因为你在计算行时耗尽了迭代器:

def stats(filename):
    ' prints the number of lines, words, and characters in file filename'
    lines = chars = 0
    words = []
    with open(filename) as infile:
        for line in infile:
            lines += 1
            words.extend(line.split())
            chars += len(line)
    print("line count:", lines)
    print("word count:", len(words))
    print("character counter:", chars)
    return len(words) > len(set(words))  # Returns True if duplicate words

或者使用文件最后的副作用来表示字符:

def stats(filename):
    ' prints the number of lines, words, and characters in file filename'
    words = []
    with open(filename) as infile:
        for lines, line in enumerate(infile, 1):
            words.extend(line.split())
        chars = infile.tell()
    print("line count:", lines)
    print("word count:", len(words))
    print("character counter:", chars)
    return len(words) > len(set(words))  # Returns True if duplicate words

答案 1 :(得分:2)

您需要在阅读完位置后使用infile.seek(0)返回文件的开头,seek(0)将其重置为开头,以便您可以重新阅读。

infile = open('data')
lines = infile.readlines()
infile.seek(0)
print(lines)
words = infile.read()
infile.seek(0)

chars = infile.read()
infile.close()
print("line count:", len(lines))
print("word count:", len(words.split()))
print("character counter:", len(chars))

输出:

line count: 2
word count: 19
character counter: 113

其他方式......

from collections import Counter
from itertools import chain
infile = open('data')

lines = infile.readlines()
cnt_lines = len(lines)

words = list(chain.from_iterable([x.split() for x in lines]))
cnt_words = len(words)

cnt_chars = len([ c for word in words  for c in word])

# show words frequency
print(Counter(words))

答案 2 :(得分:2)

在致电readlines后,您已经用尽了迭代器,您可以回头查看,但实际上您根本不需要将所有文件都读入内存:

 def stats(filename):
    chars, words, dupes = 0, 0, False
    seen = set()
    with open(filename) as f:
        for i, line in enumerate(f, 1):
            chars += len(line)
            spl = line.split()
            words += len(spl)
            if dupes or not seen.isdisjoint(spl):
                dupes = True
            elif not dupes:
                seen.update(spl)
    return i, chars, words, dupes

然后通过解包来分配值:

no_lines, no_chars, no_words, has_dupes = stats("your_file")

如果您不想包含行结尾,则可能需要使用chars += len(line.rstrip())。代码只存储所需的数据量,使用readlines,read,完整数据等等。对于大型文件,您的代码不会非常实用

答案 3 :(得分:1)

File_Name = 'file.txt'

line_count = 0
word_count = 0
char_count = 0

with open(File_Name,'r') as fh:
    # This will produce a list of lines.
    # Each line of the file will be an element of the  list. 
    data = fh.readlines()

    # Count of  total number for list elements == total number of lines. 
    line_count = len(data)

    for line in data:
        word_count = word_count + len(line.split())
        char_count = char_count + len(line)

print('Line Count : ' , line_count )
print('Word Count : ', word_count)
print('Char Count : ', char_count)