实现字典查询小工具(Python)

1、创建数据库

首先登陆远程的一个数据库,新建一个测试库,并绑定登陆用户密码

[root@V2 ~]# mysql -uroot -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 123
Server version: 5.5.56-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 
MariaDB [(none)]> create database sqlalchemy default character set utf8 collate utf8_general_ci;    
Query OK, 1 row affected (0.00 sec)            # 创建数据库时需指定字符集

MariaDB [(none)]> grant all privileges on databaseName.* to databaseUser@'%' identified by 'databasePasswd';      
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> 

这里需要注意的是:

创建数据库的时候一定要指定字符集为utf8(排序规则为utf8_general_ci)

创建数据库的时候一定要指定字符集为utf8(排序规则为utf8_general_ci)

创建数据库的时候一定要指定字符集为utf8(排序规则为utf8_general_ci)

在不指定的情况下生成数据库,创建表的时候默认的会是 CHARSET=latin1,这样将导致插入中文的时候出现乱码或者全是问号,如下所示

 - 表情来自网络 -

2、建立表结构

接着我们创建表结构

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/5/30 13:46
# @Author  : zhouyuyao
# @File    : createTable.py
import codecs

from sqlalchemy import Column, MetaData, Table
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+pymysql://databaseUser:[email protected]/databaseName')

metadata = MetaData(engine)

dictionary = Table('dictionary', metadata,
             Column('id', Integer, primary_key=True),
             Column('key', String(50)),
             Column('value', String(50))
             )
metadata.create_all(engine)

我们在远程库上可以查看到新建的表及其结构

MariaDB [(none)]> use sqlalchemy;            
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [sqlalchemy]> show tables;
+----------------------+
| Tables_in_sqlalchemy |
+----------------------+
| dictionary           |
+----------------------+
1 row in set (0.00 sec)

MariaDB [sqlalchemy]> show create table dictionary;
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                                                        |
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dictionary | CREATE TABLE `dictionary` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key` varchar(50) DEFAULT NULL,
  `value` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

MariaDB [sqlalchemy]> 

3、导入数据

接着我们将字典文件里面的数据插入至表中

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/5/29 20:48
# @Author  : zhouyuyao
# @File    : demon1.py
import codecs

from sqlalchemy import Integer, Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+pymysql://databaseUser:[email protected]/databaseName?charset=utf8')

Base = declarative_base()
class Dictionary(Base):
    __tablename__ = 'dictionary'
    id = Column(Integer, primary_key=True)
    key = Column(String(50))
    value = Column(String(50))

DBSession = sessionmaker(bind=engine)
session = DBSession()

class HandleData(object):
    def __init__(self, dataFile):
        self.dataFile = dataFile
    def make_data_to_str(self):
        with codecs.open(self.dataFile, encoding='utf-8') as file:
            for (num, value) in enumerate(file):
                line = value.strip().split()
                diction =Dictionary(id=num+1, key=line[0], value=line[1])
                session.add(diction)
        session.commit()

handleData = HandleData('dictionary.txt')
handleData.make_data_to_str()
session.close()


部分数据显示如下

4、查询单词含义

最后我们通过输入一个单词,程序则会打印出相应的含义,代码如下

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/5/30 13:47
# @Author  : zhouyuyao
# @File    : selectData.py
from sqlalchemy import create_engine, Integer, Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+pymysql://databaseUser:[email protected]/databaseName?charset=utf8')

Base = declarative_base()
class Dictionary(Base):
    __tablename__ = 'dictionary'
    id = Column(Integer, primary_key=True)
    key = Column(String(50))
    value = Column(String(50))

DBSession = sessionmaker(bind=engine)
session = DBSession()

# =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=++=+=+=+=+=+=+=+=+=+=+=+=+= #

word = input("please input your a word:")
result =session.query(Dictionary).filter(Dictionary.key.like("%{0}%".format(word))).all()
for each in result:
    print(each.id, each.key, each.value)

测试运行结果如下

但是,在一种情况下,会出现多个结果

如果我们想要精确查询单词,并且用户选择退出即退出,则我们可以在用户查询的时候进行如下优化

while 1:
    word = input("please input your a word(exit with 'q'):")
    result =session.query(Dictionary).filter(Dictionary.key.like("{0}".format(word))).all()
    for each in result:
        print(each.id, each.key, each.value)
    if word == "q":
        exit(0)

'''
exit()通常是用在子程序中用来终结程序用的,使用后程序自动结束,跳回操作系统。
exit(0) 表示程序正常退出,exit⑴/exit(-1)表示程序异常退出。
exit() 结束当前进程/当前程序/,在整个程序中,只要调用 exit ,就结束。
'''

这样我们就得到优化的结果了

参考资料

1. https://blog.csdn.net/sinat_19650093/article/details/50133631 使用mysql数据库插入中文全部变成问号

2. https://blog.csdn.net/zhouyan8603/article/details/47107041 Mysql插入中文变为全问号???的问题 解决方法

3. https://blog.csdn.net/fdipzone/article/details/18180325 深入Mysql字符集设置

4. https://www.cnblogs.com/zhangyuhang3/p/6873895.html MySQL 查看表结构简单命令

5. https://baike.baidu.com/item/Exit%28%29/1883141?fr=aladdin

猜你喜欢

转载自my.oschina.net/u/3314358/blog/1821506