利用python从《牛津高阶英汉词典》里提取单词列表
从网上下载的《牛津高阶英汉词典》是以文本的形式存在于A-Z的文件夹中。每个文件夹有多个文件。如图:
文件夹A里的文件有:
其它文件夹基本也是多个文件。
基本思路是通过文件夹遍历找出所有文件。然后对这些文件逐个应用正则表达式进行搜索,提取单词列表。经过前面若干天的学习,填了一个又一个坑,现在可以给出一个比较成熟的代码了。
import re
p=re.compile(r"\b[-a-z]{2,40}\s?\r\n")
#遍历文件夹下所有子文件夹即文件,
#返回包括子文件夹在内的全部文件
def list_all_files(dir):
import os.path
_files=[]
list=os.listdir(dir)
for i in range(0,len(list)):
path=os.path.join(dir,list[i])
if os.path.isdir(path):
_files.extend(list_all_files(path))
if os.path.isfile(path):
_files.append(path)
return _files
#用来进行单词计数
count=0
files=list_all_files("oxford-dict")
with open("listofwords.txt","w") as f:
for file in files:
f.write("\n"+file+"\n")
with open(file,"rb") as fr:
str=fr.read().decode("gbk","ignore")#别忘了“ignore”,此坑甚大。
words=re.findall(p,str)
#去除重复的单词
word_remove_duplication=[]
for word in words:
if word not in word_remove_duplication:
word_remove_duplication.append(word)
#将单词写入文本
for s in word_remove_duplication:
f.write(s)
count=count+1
f.write("单词数量大约是:{}".format(count))
输出文本如下: