用python打开某程序输入文本_用python写一个文本阅读器

现在无论在电脑上还是手机端阅读txt的小说非常方便,比如下载一个QQ阅读之类的软件就可以实现书签和翻页功能, 那么如何用python来实现同样的功能呢,我觉得这是一个非常实用并且可以锻炼我们的编程能力的小练习。

我先抛砖引玉,写一个简单的文本阅读器。

进入程序

42c2594a41e2

如果第一次使用,请打开新的txt文件

输入n, 来预览该文件夹内存放的txt文件

42c2594a41e2

n

接着输入txt文件名,

比如侠客行

42c2594a41e2

翻页

直接输入回车,便可实现翻页。

结束阅读并保存当前页为书签

输入 s 存入书签,

42c2594a41e2

s

程序提示是否结束阅读,如果是则输入回车,否则输入任意字符,继续浏览。

如果第一次创建书签,程序会创建一个bookmark.txt 的文件,并将书签保存在其中

直接结束阅读

输入b 则会阅读结束阅读,并且不保存当前页为书签。

浏览书签历史

输入v 程序会打开bookmark.txt的文件,浏览所有保存过的书签历史

42c2594a41e2

v

接着输入书签 index来跳转至该书签。

42c2594a41e2

直接继续最近一次阅读

如果直接输入 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值