莫愁前路无知己,天下谁人不识君。。。。

python 小编程-----文本写入读出打印字数行数

上一篇 / 下一篇  2017-11-01 16:01:45 / 个人分类:python 小编程

# coding:utf-8
# 在当前交互窗口写入内容,并保存在本地!
def writefile(fname):
    import os
    ls = os.linesep
    # fname = 'e:\lili.txt'
    while True:
        if os.path.exists(fname):
            print "ERROR: '%s' already exists" % fname
        else:
            break
    all = []
    print "\nEnter lines ('.' by itself to quit).\n"   # 提示语:空白行输入.退出单签程序
    while True:
        entry = raw_input('> ')
        if entry == '.':
            break
        else:
            all.append(entry)
    fobj = open(fname, 'w')
    fobj.writelines(['%s%s' % (x, ls) for x in all])
    fobj.close()
writefile('e:\lisi.txt')
# 把刚写保存的内容读出来
def readfile(fname):
    try:
        fobj = open(fname, 'r')
    except IOError, e:
        print "*** file open error:", e
    else:
        for eachLine in fobj:
            print eachLine,
        fobj.close()
readfile('e:\lili.txt')
# 打印总行数
def countLine(filename):
    return open(filename).read().count('\n')
print countLine('E:\lili.txt')
# 打印总字数(只统计中文,中文,中文)
# coding: utf-8
import json
def is_chinese(uchar):
        """判断一个unicode是否是汉字"""
        if u'\u4E00' <= uchar <= u'\u9FA5':
            return True
        else:
            return False
def count_chinese_word(filepath, encoding):
    _dict = {}
    try:
        with open(filepath, 'r') as txt_file:
            for line in txt_file:
                ustr = line.decode(encoding)
                for uchar in ustr:
                    if is_chinese(uchar):
                        if _dict.has_key(uchar):
                            _dict[uchar] += 1
                        else:
                            _dict[uchar] = 1
    except IOError as ioerr:
        print "文件", filepath, "不存在", ioerr
    return _dict
if __name__ == '__main__':
  _dict = count_chinese_word('E:\\lili.txt', 'gbk')
  a = json.dumps(_dict, encoding="utf-8", indent=4,  ensure_ascii=False)
  print a
  print type(a)  # unicode
  b = json.loads(a).values()  # 将unicode 装换成字典,并获取值放在列表中
  print sum(b)   # 获取列表总和,统计汉字个数。不统计出汉字以外的字符


TAG: Python python 文件知识

 

评分:0

我来说两句

Open Toolbar