莫愁前路无知己,天下谁人不识君。。。。
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) # 获取列表总和,统计汉字个数。不统计出汉字以外的字符
相关阅读:
- pythen+selenium精华知识之三-----滚动条(注意第四点) (cq520131517, 2017-10-23)
- Python工具箱 | 手把手教你如何强行与好久不联系的朋友制造话题 (资深梦游, 2017-10-25)
- 使用Python一秒看完十九大报告 (资深梦游, 2017-10-26)
- python 小知识2-----比较大小,日期比较 (cq520131517, 2017-10-27)
- python 小知识3--------构造函数简要 (cq520131517, 2017-10-27)
- Python学习笔记_01:基本概念介绍 (资深梦游, 2017-10-27)
- 简易Python Selenium爬虫实现歌曲免费下载 (资深梦游, 2017-10-27)
- 实用又强大,6 款 Python 时间& 日期库推荐 (资深梦游, 2017-10-30)
- Python爬虫实战:使用Selenium抓取QQ空间好友说说 (资深梦游, 2017-10-30)
- 让 Python 更加充分的使用 Sqlite3 (资深梦游, 2017-10-31)
收藏
举报
TAG:
Python
python
文件知识