如何运用python统计文件中字符个数???

先创建txt文件,内容类似这样:

python 统计文件中包含字符串的行数 python统计文件字符个数_字符串


思路一:将文件打开,去掉换行符放到列表里,再对列表进行分割,转化成字符串后进行统计

def statistics(file_name):
    with open(file_name, 'r') as f:
        list_f = [line.strip('\n') for line in f]
        cols=[]  # 创建一个空的列表
        for line in list_f: 
            list_split = line.split() # 对列表进行切片
            list_str = ''.join(list_split) # 
            cols.append(list_str)

    return '统计文件中的字符个数为:{}'.format(len(''.join(cols)))

if __name__ == '__main__':
    file_name = 'test.txt'
    print(statistics(file_name))

思路二:打开文件,获取文件所有行,将所有行按字符串连接,将连接好的字符串中的\n和空格进行替换,并打印

def statistics(file_name):
    with open(file_name, 'r') as f:
        line = f.readlines()  # 打印所有的文件内容行
    # ''.join(line) : 将列表元素按字符串连接
    # .format 字符串格式化引号中的{}
    # replace()括号中后面的双引号替换前面双引号的内容
    
    return '统计文件中的字符个数为:{}'.format(len(''.join(line).replace(" ","").replace("\n","")))

if __name__ == '__main__':
    print(statistics('test.txt'))

运行结果:
统计文件中的字符个数为:69