读取本地路径的文本文件

实现一个函数 count_file(filepath),功能为读取一个本地路径(由参数filepath指定)的文本文件,统计文本文件中的字数和行数,并返回该文本文件的字数和行数。

代码如下:

input.txt

123456
123
123

main.py

def count_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as fr:
        lines = fr.readlines()
    line_len = len(lines)
    count = 0
    for line in lines:
        _line = line.replace("\n", "")
        count += len(_line)

    return count, line_len


filename = 'input.txt'
word_count, line_len = count_file(filename)
print(f"该文本文件的行数为:{line_len}")
print(f"该文本文件的字数为:{word_count}")

输出为:

该文本文件的行数为:3
该文本文件的字数为:12


如有问题及时沟通

def count_file(filepath):
    with open(filepath, 'r', encoding = 'utf-8') as f:
        rs = [i.strip() for i in f.readlines()]
        return sum([len(i) for i in rs]), len(rs)
    
    
s = count_file(filename)
print(s)

首先先创建一个名为text.txt的文件,再创建一个名为main.py的python脚本

text.txt

1234

main.py

def count_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        content= [i.strip() for i in f.readlines()]
    return sum([len(i) for i in content]), len(content)

s = count_file('text.txt')
print(s)

输出结果:

[4, 1]

希望您能采纳此回答,谢谢!


# -*- coding: GBK -*-

import string

import sys

reload(sys)

def compareItems((w1,c1), (w2,c2)):

if c1 > c2:

return - 1

elif c1 == c2:

return cmp(w1, w2)

else:

return 1

def main():

fname = "file.txt"

try:

text = open(fname,'r').read()

text = string.lower(text)

except:

print "\nfile.txt is not exist!!! or There is a R/W error! "

sys.exit()

for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':

text = string.replace(text, ch, ' ')

words = string.split(text)

counts = {}

for w in words:

counts[w] = counts.get(w,0) + 1

n = input("\n输入要统计的top单词数:")

items = counts.items()

items.sort(compareItems)

max = len(items)

print "\n单词总计:" + str(len(words))

print "单词净个数(已去重):" + str(max)

print "\n"

if n > max:

n = max

for i in range(n):

print "%-10s%5d" % items[i]

if __name__ == '__main__':

main()