用python寫一個文本閱讀器

現在無論在電腦上還是手機端閱讀txt的小說非常方便,比如下載一個QQ閱讀之類的軟件就可以實現書簽和翻頁功能, 那么如何用python來實現同樣的功能呢,我覺得這是一個非常實用并且可以鍛煉我們的編程能力的小練習。

我先拋磚引玉,寫一個簡單的文本閱讀器。

進入程序

如果第一次使用,請打開新的txt文件

輸入n, 來預覽該文件夾內存放的txt文件

n

接著輸入txt文件名,

比如俠客行

翻頁

直接輸入回車,便可實現翻頁。

結束閱讀并保存當前頁為書簽

輸入 s 存入書簽,

s

程序提示是否結束閱讀,如果是則輸入回車,否則輸入任意字符,繼續瀏覽。

如果第一次創建書簽,程序會創建一個bookmark.txt 的文件,并將書簽保存在其中

直接結束閱讀

輸入b 則會閱讀結束閱讀,并且不保存當前頁為書簽。

瀏覽書簽歷史

輸入v 程序會打開bookmark.txt的文件,瀏覽所有保存過的書簽歷史

v

接著輸入書簽 index來跳轉至該書簽。

直接繼續最近一次閱讀

如果直接輸入 c 可以自動從最新的書簽記錄處開始,直接繼續最近一次閱讀。

結束程序

輸入e 來終止程序

程序本身并不復雜,由于我用的是python2, 對于如何處理中文編碼是一個很好的練習。

Code:


# coding=utf-8


import os
import os.path
import argparse
import sys
import datetime
import time
import random
from os.path import getsize
from StringIO import StringIO
import json
from pprint import pprint
import re
import codecs



class Reader:


    def __init__(self):
        os.system('cls')
        self.load_bookmark()
        print """

 _       __     __                             __           ______     __     ____                 __         
| |     / /__  / /________  ____ ___  ___     / /_____     /_  __/  __/ /_   / __ \___  ____ _____/ /__  _____
| | /| / / _ \/ / ___/ __ \/ __ `__ \/ _ \   / __/ __ \     / / | |/_/ __/  / /_/ / _ \/ __ `/ __  / _ \/ ___/
| |/ |/ /  __/ / /__/ /_/ / / / / / /  __/  / /_/ /_/ /    / / _>  </ /_   / _, _/  __/ /_/ / /_/ /  __/ /    
|__/|__/\___/_/\___/\____/_/ /_/ /_/\___/   \__/\____/    /_/ /_/|_|\__/  /_/ |_|\___/\__,_/\__,_/\___/_/     
                                                                                                              

                """


    def Read_txt(self,Use_bm):
        

        if Use_bm ==True:
            self.text_name=self.bm[1]
            self.last_page_num=self.bm[3]
            print "\nWelcome back to "+ self.text_name +".txt" +"  --last time read at ["+self.bm[2]+"]  --read from page " +self.bm[3] +"\n"

        else:
            which_text = raw_input('Input your new text name: \n')
            self.text_name=which_text
            self.last_page_num=0
            print "\nNow, you are reading " + self.text_name +".txt" +"\n"



        i =0
        with codecs.open(self.text_name+".txt", encoding="utf-8") as g:
            line_text = g.readlines()

        g.close()
        for l in line_text:
            if i>=int(self.last_page_num)-8:

                
                print l.encode("gb18030")
                if i%9 ==0:
                    print "------------------"
                    next = raw_input( '\n')
                    if next =="c":
                        os.system('cls')
                        
                    elif next=="s":
                        
                        print "--saved to your bookmark"
                        
                        bk = codecs.open("bookmark.txt", "a", "utf-8")
                        if Use_bm==True:
                            bm_= "["+self.text_name+"]  ["+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +"]  ["+str(i) +"]\n"
                        else:
                            bm_= "["+self.text_name.decode("gb18030")+"]  ["+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +"]  ["+str(i) +"]\n"

                        
                        bk.write(bm_)
                        bk.close()
                        next = raw_input( 'exit?\n')
                        if next =="":
                            os.system('cls')
                            break



                    elif next =="b":
                        os.system('cls')
                        break
                    elif next =="h":
                        print """
                        type those commands

                        Enter - next page
                        s - save and exit
                        b - exit without save

                        """

            i=i+1







    def load_bookmark(self):
        if os.path.isfile("bookmark.txt"):
            self.bm_file_exist= True

            with codecs.open("bookmark.txt", encoding="utf-8") as bm:
                line_bm = bm.readlines()
            self.bm_list= []
            bm.close()
            index=0
            for each_bm in reversed(line_bm):
    
                text_name = re.search(r"\[(.*)\]\s+\[(.*)\]\s+\[(\d*)\]", each_bm).group(1)
                bm_date_time = re.search(r"\[(.*)\]\s+\[(.*)\]\s+\[(\d*)\]", each_bm).group(2)
                page_num = re.search(r"\[(.*)\]\s+\[(.*)\]\s+\[(\d*)\]", each_bm).group(3)
                self.bm_list.append([index,text_name,bm_date_time,page_num])
                index=index+1
        else:
            self.bm_file_exist= False


    def choose_bookmark(self,Use_default_bm):
        self.load_bookmark()
        
        if Use_default_bm== True:
            self.bm=self.bm_list[0]
        else:
            for each_bm in self.bm_list:
                print "Index :"+ str(each_bm[0])+" --"+ each_bm[1]+" "+each_bm[2]+" "+each_bm[3]
            choose_bm = raw_input('which bookmark?: \n')
            index=re.search(r"(\d*)", choose_bm).group(1)
            self.bm=self.bm_list[int(index)]





    def interface(self):
        while True:
            nb = raw_input('Give me your command: \n')

            if nb.startswith('v') == True:
                os.system('cls')
                if self.bm_file_exist ==True:
                    self.choose_bookmark(False)
                    self.Read_txt(True)
                else:
                    print "no bookmark has been created yet"

            elif nb.startswith('n') == True:
                os.system('cls')

                files = [f for f in os.listdir('.') if os.path.isfile(f)]
                print "text files in current folders---"
                for f in files:
                    if f.endswith(".txt"):
                        print f
                print "\n\n"
                self.Read_txt(False)
            elif nb.startswith('c') == True:
                os.system('cls')
                self.choose_bookmark(True)
                self.Read_txt(True)

            elif nb == "e":
                os.system('cls')
                print "bye bye"
                break
            else:
                
                print """

                Commands :

                v - view bookmark

                c - continue to read from last time

                n - open a new txt file

                e - exit 

                """


app=Reader()

app.interface()

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容