#读取一个纯英文的文本文件,统计其中每个单词的出现次数,并将次数和其单词本身存入mysql数据库
import  re
import MySQLdb
#读取文件信息
filename="word.txt"
#使用open方法操作文本文件,r表示以只读方式打开文件。文件的指针将会放在文件的开头
f=open(filename,'r')
#使用f.read方法返回整个文本文件给article,
artical=f.read()
#使用f.close关闭文件
f.close()
#将文本中的所有英文单词筛选出来 去掉标点和其他文本符号  并且将单词都小写保存在数组List中
List=[]
#'[a-zA-Z]+'正则表达式,表示大小写a-z出现一次或连续出现,这里表达一个单词
#使用re.findall方法,从article中获取单词,作为list存入word中
word=re.findall('[a-zA-Z]+',artical)
for i in word:
    List.append(i.lower())
#把单词与出现的次数存入数据库(我也不知道为什么要存进去:)
def save_sql(word,numbers):
    host = ("localhost")
    user = ("root")
    pass_ = ("123456")
    db = ("sqlforpy")
    #建立连接
    connect = MySQLdb.connect(host,user,pass_,db)
    #使用cursor()方法获取操作游标 (在操作游标中才可进行数据库操作
    cursor = connect.cursor()
    #使用insert into进行插入数据
    sql = "insert into count_word(word,numbers)VALUES('%s','%d')" % (word,numbers)
    #执行sql语句
    try:
        cursor.execute(sql)
        #使用commit提交到数据库执行保存
        connect.commit()
    except:
        #发生错误时回滚
        connect.rollback()
    #关闭连接
    connect.close()
#统计单词数目
print("%s总共有%d个单词" %(filename,List.__len__()))
#统计各个单词出现的频率,并且按照字典顺序输出并将内容写入文件中
#f=open("result.txt",'w')
List=sorted(List)
i=0
for i in range(0,List.__len__()-1):
    #使用count方法获得字符串出现的次数
    count=List.count(List[i])
    if(List[i]!=List[i+1]):
        #print(List[i]+"  "+str(count)+"\n")
        #f.write(List[i]+"  "+str(count)+"\n")
        save_sql(List[i],count)