从一个文件的章节创建多个文件

时间:2017-10-19 15:41:33

标签: python

我尝试根据文件的章节创建文件

内容为

的文件learn.md
## 1.Py Ingredients: Numbers, Strings, and Variables

In this chapter we’ll begin by looking at Python’s simplest built-in data types:

## 2.Py Filling: Lists, Tuples, Dictionaries, and Sets

We started at the bottom with Python’s basic data types: booleans, integers, floats, and strings.

## 3.Py Crust: Code Structures

我的尝试:

1.阅读其内容

with open('learn.md') as file:
    content = file.read()

2.分为章节并获取每章的内容

delimiter = '## '
def get_contents_list(content, delimiter):
    contents_list = content.split(delimiter)
    #validate the lists
    contents_list = [ i for i in contents_list if len(i) > 10]
    # Add delimiter back to each chapter's content
    contents_list = [ delimiter+i for i in contents_list]
    return contents_list
In [9]: contents_list = get_contents_list(content, delimiter)

3.获取具有已定义功能的标题

def get_headers_list(contents_list,delimiter):
    headers_list = []
    count = 0
    for ele in contents_list:
        count += 1
        start_index = len(delimiter)
        end_index = ele.index('\n\n')
        ele = ele[start_index:end_index]
        ele = ele.strip()
        ele = ele.replace(' ','_')
        ele += '.md'
        headers_list.append(ele)
    return headers_list

输出:

In [32]: headers_list = get_headers_list(contents_list,delimiter)
In [33]: headers_list
Out[33]:
['1.Py_Ingredients:_Numbers,_Strings,_and_Variables.md',
 '2.Py_Filling:_Lists,_Tuples,_Dictionaries,_and_Sets.md',
 '3.Py_Crust:_Code_Structures.md']

4.定义write功能

def write(filename,content):
    with open(filename, 'w') as file:
        file.write(content)

5.创建文件

for header, content in zip(headers_list, contents_list):
    write(header,content)

问题通过冗长的步骤解决,而每天都经常进行。 如何通过魔法访问来处理它。

1 个答案:

答案 0 :(得分:0)

尝试组合数据和功能的class 而不仅仅是功能。

import os
import os.path

class CreateFile:

    '''mydict = {'filename': '',
              'file_dir': '',
              'dilimiter': '',
              'target_dir': ''}'''

    def __init__(self, **kwargs):


        self.file_dir = kwargs['file_dir']
        self.delimiter = kwargs['delimiter']
        self.filename = kwargs['filename']
        self.target_dir = kwargs['target_dir']
        self.kwargs = kwargs


    def read(self,filename):
        with open(self.filename) as file:
            content = file.read()
            return content

    def write(self, filename,content):
        with open(filename, 'w') as file:
            file.write(content)

    def get_contents_list(self):
        # import os
        os.chdir(self.file_dir)

        content = self.read(self.filename)
        delimiter = self.delimiter
        contents_list = content.split(delimiter)
        #validate the lists
        contents_list = [ i for i in contents_list if len(i) > 10]
        # Add delimiter back to each chapter's content
        contents_list = [ delimiter+i for i in contents_list]
        return contents_list

    def get_headers_list(self):
        # import os.path
        contents_list = self.get_contents_list()
        delimiter = self.delimiter
        target_dir = self.target_dir
        headers_list = []
        count = 0
        for ele in contents_list:
            count += 1
            start_index = len(delimiter)
            end_index = ele.index('\n\n')
            ele = ele[start_index:end_index]
            ele = ele.strip()
            ele = ele.replace(' ','_')
            ele += '.md'
            print('file%d: ' %count,ele)
            ele = os.path.join(target_dir,ele)
            print('path%d: ' %count, ele)
            print()
            headers_list.append(ele)
        return headers_list

    def create(self):
        # import os
        # import os.path
        contents_list = self.get_contents_list()
        headers_list = self.get_headers_list()
        alt = input('Confirmed to continue: ').lower()
        if alt != 'y':
            return
        for header, content in zip(headers_list, contents_list):
            self.write(header,content)

    def __str__(self):
        return self.kwargs