python 以文档形式读入读出

对之前的代码总结。

python3方法1:文档以.json格式保存在文件夹中,文件夹只有单层,对文件夹中文档进行分个读取(应用见20170525-052501.py)

 1     path = r‘C:\Users\user\Desktop\heilongjiang.dbw.cn\\‘
 2     documents = []
 3     num = 0
 4     for file in os.listdir(path)[0:]:
 5         file = path + file
 6         if not file.endswith(‘.json‘): continue
 7         f = open(file, ‘rt‘, encoding=‘utf-8‘)
 8         data = f.read()
 9         body = json.loads(data)
10
11         content = body[‘content‘]
12         # print(content)
13         num += 1
14         print(num, ‘ ‘, file)
15         documents.append(fenci(content))

python2方法2:文件夹下还有文件夹(有类别目录),多类别文档读取。(应用见20170530-corpus_segment.py)

 1     corpus_path = "train_corpus_small/"  # 未分词分类语料库路径
 2     seg_path = "train_corpus_seg/"  # 分词后分类语料库路径
 4     catelist = os.listdir(corpus_path)  # 获取corpus_path下的所有子目录
 5
 6     # 获取每个目录下所有的文件
 7     for mydir in os.listdir(corpus_path):
 8         class_path = corpus_path + mydir + "/"  # 拼出分类子目录的路径
 9         seg_dir = seg_path + mydir + "/"  # 拼出分词后语料分类目录
10         if not os.path.exists(seg_dir):  # 是否存在目录,如果没有创建
11             os.makedirs(seg_dir)
12         file_list = os.listdir(class_path)  # 获取class_path下的所有文件
13         for file_path in file_list:  # 遍历类别目录下文件
14             fullname = class_path + file_path  # 拼出文件名全路径
15             content = readfile(fullname).strip()  # 读取文件内容
16             content = content.replace("\r\n", "")  # 删除换行和多余的空格 \r\n
17             content_seg = jieba.cut(content.strip())  # 为文件内容分词
18             savefile(seg_dir + file_path, " ".join(content_seg))  # 将处理后的文件保存到分词后语料目录

python2中对于读取编码问题的解决方案:(应用参见20170530-test3.py)

 1     corpus = []
 2     tfidfdict = {}
 3     for file_path in os.listdir(start_path):
 4         fullname = start_path + file_path
 5         content = readfile(fullname).strip()
 6         #content = content.decode(‘gbk‘,‘ignore‘).encode(‘utf-8‘)
 7         content = content.replace("\r\n", "")
 8         content = content.decode(‘utf-8‘)
 9         content_seg = jieba.cut(content.strip())
10         savefile(end_path + file_path, " ".join(content_seg))
11     for file_path in os.listdir(end_path):
12         fullname = end_path + file_path
13         content = readfile(fullname).strip()
14         content = content.decode(‘utf-8‘)
15         content = content.replace("\r\n", "").strip()
16         corpus.append(content)
17         #print corpus
18     for i in range(len(corpus)):
19         print str(corpus[i])

还有一个问题:为什么在sys.setdefaultencoding之前要写reload(sys)

1 import sys
2 reload(sys)
3 sys.setdefaultencoding(‘utf8‘)

参考文档:http://www.360doc.com/content/15/0105/15/9934052_438371998.shtml

研究python的模块加载过程,在sys加载后,setdefaultencoding方法被删除了,所以我们要通过重新导入sys来设置系统编码。

时间: 2024-08-10 05:23:40

python 以文档形式读入读出的相关文章

Python 单元测试 & 文档测试

1.1   单元测试 1.1.1   单元测试编写 单元测试是用来对一个模块.一个函数或者一个类来进行正确性检验的测试工作. 编写一个Dict类,这个类的行为和dict一致,但是通过属性来访问. >>> d = Dict(a=1, b=2) >>> d['a'] 1 >>> d.a 1 class dict编写如下: [[email protected] python]# cat mydict.py #!/usr/bin/python # -*- co

如何查询python帮助文档;sublime 快捷键

# 帮助文档 1.dir函数式可以查看对象的属性:Python命令窗口输入 dir(str) 即可查看str的属性. 2. 如何查看对象某个属性的帮助文档 ? 如要查看str的split属性,可以用__doc__(双下划线), 使用方法为print(str.split.__doc__) 或者help函数,使用方法为help(str.split). 要注意在python3.4中查看其它模块的对象属性要在help函数中加上‘’,help('time.strftime'): 或者先加载模块 impor

如何在命令行模式下查看Python帮助文档---dir、help、__doc__

如何在命令行模式下查看Python帮助文档---dir.help.__doc__ 1.dir函数式可以查看对象的属性,使用方法很简单,举str类型为例,在Python命令窗口输入 dir(str) 即可查看str的属性,如下图所示: 2.如何查看对象某个属性的帮助文档 ?如要查看str的split属性,可以用__doc__, 使用方法为print(str.split.__doc__),如下图所示: 3.查看对象的某个属性还可以用help函数,使用方法为help(str.split),如下图所示:

python统计文档中词频

python统计文档中词频的小程序 python版本2.7 程序如下,测试文件与完整程序在我的github中 1 #统计空格数与单词数 本函数只返回了空格数 需要的可以自己返回多个值 2 def count_space(path): 3 number_counts = 0 4 space_counts = 0 5 number_list = [] 6 7 with open(path, 'r') as f: 8 for line in f: 9 line = line.strip() 10 sp

Python学习文档指引

Python文档资源: 形式 角色 #注释 文件中的文档 dir函数 对象中可用属性的列表 文档字符串:__doc__ 附加在对象上的文件中的文档 PyDoc:help函数 对象的交互帮助 PyDoc:HTML报表 浏览器中的模块文档 标准手册 正式的语言和库的说明 网站资源 在线教程.例子等 出版的图书 商业参考书籍 1.#注释 #注释只能从源代码文件中看到,若要查看#注释信息,只需要获取相应的模块文件即可. 2.Dir函数 获取对象内可用所有属性列表的简单方式(如,对象的方法以及简单的数据项

使用sphinx快速生成Python API 文档

一  简单介绍 不管是开源还是闭源,文档都是很重要的.当然理论上说,最好的文档就是代码本身,但是要让所有人都能读懂你的代码这太难了.所以我们要写文档.大部分情况,我们不希望维护一份代码再加上一份文档,这样做很容易造成文档和代码的不一致,程序员最讨厌更新文档了.所以最佳实践就是在程序员代码中加注释,然后通过构建脚本自通生成文档,包括html,latex,pdf等. 对应于Pyhon,有很多可供选择的工具: sphinx中文版介绍 Sphinx使用 reStructuredText作为标记语言(类似

python log文档

在使用python的过程中,错误检查一直都是个大难题,这里提供一种打印log文件的方式,</span> 即记录python运行过程的文档,能够有效的帮助你定位错误 代码: import mprint logfile = 'setup.log' log = mprint.MPRINT(logfile,'w') log._print("error") 可以再你需要的任何地方使用log._print() 输出内容

零基础学python-14.3 python的文档资源:help函数

python除了提供__doc__来查询文档字符串,还提供另外的一种方法来查询文档字符串:help 下面是我们自己建立的一个类,使用help打印,形成相关的报表信息 >>> class Test(): '这是一个测试类' def helloworld(): '测试方法' print('hello world') >>> help(Test) Help on class Test in module __main__: class Test(builtins.object

零基础学python-14.2 python的文档资源:文档字符串

这一章节我们来说说文档字符串:__doc__ 文档字符串其实也是注释的一种,但是它一般放在模块文件.函数或者类语句的顶部,主要用来说明它们是干什么的,为什么这样做 python会自动封装这些文字,放到__doc__属性里面 >>> def test(): '这是一个测试方法' print('hello world') >>> test.__doc__ '这是一个测试方法' >>> >>> class Test(): '这是一个测试类'