利用re库实现对表格内指定列数据的模糊搜索(低配版)

上文说获取到火车站的三字码存储于表格文件内。但是单单存储是不够用的,毕竟我们需要指定站点的三字码来获取指定站点的车次信息,所以考虑通过re库+xlrd库实现对表格内指定列的内容搜索从而输出指定列的某一整行的内容。
上文地址

注意
此代码虽以前文所提的火车站的三字码为例,不过个人认为若暂时无法找到合适的模糊搜索的方法同时又没有特别高的要求时,可以利用此种方法实现。

所用样表部分数据截图
利用re库实现对表格内指定列数据的模糊搜索(低配版)_第1张图片
实现原理
通过查询B列(汉字列)内容结合正则表达式'(.{0,}'+str(name)+'.{0,})'(name为用户输入的内容,前后的.{0,}表示可以共同或单独匹配前后的任意长度字符),将匹配到的数据的一整行数据存入temp_list字典内,将匹配的列内的数据存入city_seach列表内,提供选择。同时提供错误重新输入与查询退出。

代码以及部分注释如下

import os
import re
import xlrd
def seach_xlsx(name=''):
    data = xlrd.open_workbook ( './city_list.xlsx' )#打开xlsx文件,文件名city_list
    table = data.sheet_by_name ( 'sheet1' ) #文件内存储数据的工作表名叫 sheet1
    nRow = table.nrows					#统计列数,三列数据一样长度
    temp_list = {
     }						#用于暂存模糊搜索时的符合要求的整行数据
    city_seach = []						#用于暂存模糊搜索时符合要求的列数据
    count = 0							#计数,如何未找到需搜索内容,count的值与nRow相等
    i = 0								
    while i<nRow:
        if re.findall('(.{0,}'+str(name)+'.{0,})',str ( table.row_values ( i )[ 1 ] )) != []:
            a = re.findall('(.{0,}'+str(name)+'.{0,})',str ( table.row_values ( i )[ 1 ] ))[0]
            city_seach.append(a)
            temp_list[str(a)] = str(table.row_values ( i )[ 0 ] )+'|'+str(table.row_values ( i )[ 1 ] )+'|'+str(table.row_values ( i )[ 2 ] )
            i += 1
        #重新输入查询与查询退出
        elif re.findall('(.{0,}'+str(name)+'.{0,})',str ( table.row_values ( i )[ 1 ] )) == []:
            count += 1
            if count == nRow-1:
                count = 0
                name = input('请重现输入(输入0退出):')
                if name == '0':
                    break
                i = 0
            else:
                i+=1
    if temp_list == {
     } or city_seach == []:
        return
    else:
        print(city_seach)
        print(temp_list)
        name_id = eval(input("请输入详细地址索引号(从1开始):"))
        print(temp_list[str(city_seach[name_id-1])])
        return  temp_list[str(city_seach[name_id-1])]
#用os库判断文件是否存在,不存在则去利用get_city_list函数生成
def seach_main(s=''):
    if os.path.exists('./city_list.xlsx'):
        name = input(''+str(s)+'')
        return seach_xlsx(name)
    else:
        get_city_list ()
        seach_main(s)
seach_main('请输入始发站:')
seach_main('请输入终点站:')

实现后截图
利用re库实现对表格内指定列数据的模糊搜索(低配版)_第2张图片
搜索“京”字时反馈数据
利用re库实现对表格内指定列数据的模糊搜索(低配版)_第3张图片
搜索“上海”时的反馈数据
利用re库实现对表格内指定列数据的模糊搜索(低配版)_第4张图片

你可能感兴趣的:(正则表达式,爬虫,python)