项目存储在https://gitee.com/xiehh18/python_learn_-english
import os
y=[x for x in os.listdir('.') if os.path.isfile(x)]
for _ in range(len(y)):
print(_,y[_])
ind=input('Input the index of file your want to read\n')
ind=int(ind)
if(ind<len(y) and ind>=0):
filename=y[ind]
else:
exit()
#filename=input('Please input the name of file you want to read\n')
err,count=0,0
with open(filename,mode='r') as x:
docs=[i.strip() for i in x if i.strip()!='' ]
t,i='',0
while i<len(docs) and t!='exit' :
k=docs[i]
t=''
#print(i,'/',len(docs),'error times:',err)
while t!=k and t!='next' and t!='previous' and t!='exit' :
if(t!=''):
err=err+1
print(k)
print(i,'/',len(docs),'error times:',err,', repeat it:')
t=input()
if t=='previous' and i>0:
i=i-2
print('---Previous---',i,'/',len(docs),'error times:',err)
elif t=='next':
print('---Next---',i,'/',len(docs),'error times:',err)
elif t=='exit':
i=len(docs)-1
print('---End---',i,'/',len(docs),'error times:',err)
i=i+1
print('Ok!')
#print('The times of error is ' ,err,', error rate is', err/count)
以上代码实现简单工作:读取一个文本文件,然后逐行打印,每一行打印后可以选择重复该行文字。可以用来读取一个英语文章的文本,然后不断的重复输入其中的语句来熟练一些英语语法。
import json
import os
from bs4 import BeautifulSoup as bs #the tool to parse webpage
import requests #
class dictbook:
def __init__(self):
self.filelists=[x for x in os.listdir('.') if os.path.isfile(x)]
self.dicts=[x for x in self.filelists if x.endswith('.json')]
self.fn='.dictnotes.json'
self.ls={
}
self.ls['index']=0
self.notes={
}
self.header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0"}
if self.fn not in self.filelists:
self.ls['dicts']=[]
if len(self.dicts)!=0:
print('You have some json files as follws, do you want to add them')
for ind, x in enumerate(self.dicts):
print(ind,x)
ind=0
while len(self.ls['dicts'])<=len(self.dicts) and ind <len(self.dicts):
ind=input('Enter the index of json file you want to add:')
ind= int(ind)
if(ind>=0 and ind <len(self.dicts) and self.dicts[ind] not in self.ls['dicts'] ):
self.ls['dicts'].append(self.dicts[ind])
with open(self.fn,'w') as fw:
json.dump(self.ls,fw)
print('Do you want to create a dictnote now? y/n')
ans=input()
if(ans=='y'):
fnames=input('Enter a name: ')
self.create(fnames)
else:
with open(self.fn, 'r') as jr:
self.ls=json.load(jr)
self.showdicts()
self.check()
#ind=input('Chose your dictnotes:')
self.newDicts=''
self.newTrans=''
#ind=int(ind)
def create(self,fname):
if not fname.endswith('.json'):
fname=fname+'.json'
if fname not in self.ls['dicts']:
self.ls['dicts'].append(fname)
with open(self.fn,'w') as fw:
json.dump(self.ls,fw)
def add(self,fname):
self.create(fname)
def delate(self,fname):
if(fname in self.ls['dicts']):
self.ls[dicts].remove(fname)
def showdicts(self):
for ind,x in enumerate(self.ls['dicts']):
print(ind,x)
def shownotes(self):
self.check()
ind = 1
print('The dicts lists are given by:')
if len(self.notes) > 0:
for keys, values in self.notes.items():
print(ind, keys, values)
ind = ind+1
def select(self,ind):
if(ind>=0 and ind<len(self.ls['dicts'])):
self.ls['index']=ind
with open(self.fn, 'w') as fw:
json.dump(self.ls, fw)
fns = self.ls['dicts'][ind]
if fns not in self.dicts:
print('This notes have no dicts now, do you want to add some dicts? y/n')
self.notes={
}
#keys,values='',''
ans=input()
while ans=='y':
d=input('Enter new word: ')
self.search(d)
ans=input('add it? y/n ')
if ans=='y':
self.addit()
else:
ans=input('Continue? y/n ')
self.shownotes()
ans=input('save them to your dictnotes? y/n ')
if (ans=='y'):
with open(fns,'w') as fw:
json.dump(self.notes,fw)
self.dicts = [x for x in self.filelists if x.endswith('.json')]
self.notesInfo()
def saveTonotes(self):
fns = self.ls['dicts'][self.ls['index']]
with open(fns, 'w') as fw:
json.dump(self.notes, fw)
def notesInfo(self):
ind=self.ls['index']
if(ind >= 0 and ind < len(self.ls['dicts'])):
fns = self.ls['dicts'][ind]
if fns not in self.dicts:
print('None info for your notes.')
else:
with open(self.ls['dicts'][ind], 'r') as jr:
self.notes = json.load(jr)
print('Your dictnotes ',self.ls['dicts'][ind],' have ',len( self.notes), ' dicts')
def EngToCn(self):
self.check()
self.recite2(self.notes)
def chToEn(self):
self.check()
self.recite1(self.notes)
def recite1(self,notes): #
ind=0
lists=[x for x in notes.keys()]
ans=''
notesl=[]
while ans!='c' and len(lists)>0:
if ans!='a':
notesl.clear()
for x in range(10):
if x<len(lists):
#print(x,lists[x],notes[lists[x]])
notesl.append(lists[x])
lists.remove(lists[x])
else:
for x in range(10):
print('____________________\n\n\n________________________')
print('Start it!')
for ind,en in enumerate(notesl) :
print(notes[en], ', translate, ',ind,'/',len(notesl))
ans=input()
while ans != en and ans != 'q':
ans = input('No, again (a) or look at the answer and skip (b) or quit (q):')
if ans == 'b':
print(en)
ans = en
elif ans == 'a' or ans != 'q':
print(notes[en], '-->')
elif ans=='q':
break
for ind,en in enumerate(notesl):
print(ind,en,notes[en])
ans=input('a. again b. next c.quit: ')
print('ok')
def recite2(self,notes):
ind=0
lists = [x for x in notes.keys()]
ans = 'b'
notesl = []
while ans != 'c' and len(lists) > 0:
if ans == 'b':
notesl.clear()
for x in range(10):
if x < len(lists):
#print(x, lists[x], notes[lists[x]])
notesl.append(lists[x])
lists.remove(lists[x])
elif ans=='a':
for x in range(10):
print('____________________\n\n\n________________________')
print('Start it!')
for ind, en in enumerate(notesl):
print(en, ', 1. remember 2. foget 3. quit')
ans=input()
if ans=='2':
print(notes[en])
print('--next--',ind,'/',len(notes))
elif ans=='3':
break
for ind, en in enumerate(notesl):
print(ind, en, notes[en])
ans = input('a. again b. next c.quit: ')
print('ok')
def check(self):
if(len(self.notes)==0):
self.select(self.ls['index'])
def prase_str_to_dicts(self,strs):
notes={
}
lists = strs.split('\n\n\u3000\u3000')
for x in lists :
rows=x.split('/')
notes[(rows[0]).strip()]='/'+rows[1]+'/ '+rows[2]
return notes
def addall(self,a,b):
for k,v in b.items():
a[k]=v
return a
def search(self,dicts):
self.newDicts=dicts
url = 'http://dict.youdao.com/search?q='+dicts+'&keyfrom=new-fanyi.smartResult'
t=requests.get(url,self.header)
s=bs(t.text,'lxml')
k = s.select('#phrsListTab > div.trans-container > ul')
if len(k)<1:
print('None be found!')
return 0
k1 = s.select('#phrsListTab > h2 > div > span:nth-child(1) > span')
k2 = s.select('#phrsListTab > h2 > div > span:nth-child(2) > span')
temp=k[0].decode().split('\n' )
strs = k1[0].decode().split('>')[1].split('<')[0] +','+ \
k2[0].decode().split('>')[1].split('<')[0]+' '
for x in temp[1:]:
strs=strs+x.split('')[0]+';\n'
print(strs)
self.newTrans=strs
def addit(self):
self.notes[self.newDicts]=self.newTrans
#self.saveTonotes()
def addNew(self,dicts):
self.search(dicts)
self.addit()
def repeat(self):
y = [x for x in os.listdir('.') if os.path.isfile(x) and x.endswith('.txt')]
for _ in range(len(y)):
print(_, y[_])
ind = input('Input the index of file your want to read\n')
ind = int(ind)
if(ind < len(y) and ind >= 0):
filename = y[ind]
else:
exit()
#filename=input('Please input the name of file you want to read\n')
err, count = 0, 0
with open(filename, mode='r') as x:
docs = [i.strip() for i in x if i.strip() != '']
t, i = '', 0
while i < len(docs) and t != 'exit':
k = docs[i]
t = ''
#print(i,'/',len(docs),'error times:',err)
while t != k and t != 'next' and t != 'previous' and t != 'exit':
if(t != ''):
err = err+1
print(k)
print(i, '/', len(docs), 'error times:', err, ', repeat it:')
t = input()
if t == 'previous' and i > 0:
i = i-2
print('---Previous---', i, '/', len(docs), 'error times:', err)
elif t == 'next':
print('---Next---', i, '/', len(docs), 'error times:', err)
elif t == 'exit':
i = len(docs)-1
print('---End---', i, '/', len(docs), 'error times:', err)
i = i+1
print('Ok!')
简单地实现了用json来存储单词本