Python编程快速上手》看的太快了,好多基础没彻底掌握,写这个小玩意就当复习巩固一下。开始的时候想着用 string.isalpha() 来判断英文,加入列表,结果不知道为什么中文也进去了。 接着开始写函数来判断,结果........文本里有各种标点,空格,括号,一同瞎忙乎,没啥鸟用。 最后发现还是regex最牛逼,直接全提取出来了。 不过还是收获满满,虽然做了好多无用功,但是对这些基础的更了解了。收获远远大于预期写出来。
用途:
将百度搜索到到英语词汇表,保存为txt文件。自动分解成中文与英文。拼写错误会自动记录在对应日期的txt中。下次继续加入新的生词本中,直到真正掌握。传说中的艾兵浩斯学习法?
import re
import string
import time
FILE_PATH = r'.\小学一年级.txt'
WRONG_WORDS = []
DATE_TIME = time.strftime("%Y-%m-%d", time.localtime())
#数字符号中文大于字母视作中文
def mixed_word(word):
english = 0
chinese = 0
number = 0
other = 0
for letter in word:
if word >= u'\u4e00' and word <= u'\u9fa5':
chinese += 1
elif word >= u'\u0030' and word <= u'\u0039':
number += 1
elif (word >= u'\u0041' and word <= u'\u005a') or (word >= u'\u0061' and word <= u'\u007a'):
english += 1
else:
other += 1
if english < chinese + number + other:
return "chinese"
else:
return "english"
# 判断是否是纯中文
def is_all_chinese(word):
for i in word:
if not '\u4e00' <= i <= '\u9fa5':
return False
return True
# 判断是否是纯英文
def is_all_english(word):
for i in word:
if i not in string.ascii_lowercase+string.ascii_uppercase:
return False
return True
# 中文转换成unicode
def chinese_to_unicode(word):
ret = ''
for v in word:
ret = ret + hex(ord(v)).upper().replace('0X', '\\u')
return ret
#生成中英文列表
def get_words():
file = open(FILE_PATH, encoding="utf-8").read()
ds = re.compile(r'\d{1,3}\.')
# chinese = re.compile(r'[,\)\(,……]*[\u4e00-\u9fa5]+\s+[,\)\(,……]*[\u4e00-\u9fa5]*[,\)\(,……]?[\u4e00-\u9fa5]*[,\)\(,……]*[\u4e00-\u9fa5]*[,\)\(,……]*|\d+')
chinese = re.compile(r'[…\(\),…]?[\u4e00-\u9fa5]+\s?[…\(\),…\u4e00-\u9fa5]*|\d+')
english = re.compile(r'[a-zA-Z]{1,20}\D[a-zA-Z]{1,20}|[a-zA-Z]{1,20}')
file = re.sub(ds,"",file)
chinese = chinese.findall(file)
english = english.findall(file)
return chinese, english
#默写开始啦
def spell_words(chinese,english):
wrong_times = 0
if len(chinese) == len(english):
for i in range(len(chinese)):
spell = input("%s 的英文是:\n"%chinese[i])
if spell != english[i] :
wrong_times += 1
wrong_txt = open(r'.\%s.txt'%DATE_TIME,'a', encoding="utf-8")
wrong_txt.write("%s %s"%(english[i],chinese[i]))
print("答错了,应该是 %s 。这个单词记录到错词本了。"%english[i])
elif spell == english[i]:
print("真不错,你答对了!")
print("一共%i个单词,答对了%i个,错了%i个。"%(len(english),len(english)-wrong_times,wrong_times))
else:
print("字典数量不符!\n"*10)
if __name__ == "__main__":
chinese,english=get_words()
spell_words(chinese,english)