Python txt文件加入字典并查询的方法

作者:谁谁的博客 时间:2021-11-09 12:50:15 

如下所示:


dicFile = open('train_1.txt', 'r')#打开数据  
print '开始装载数据...'  
txtDict = {}#建立字典  
while True:  
    line = dicFile.readline()  
    if line == '':  
        break  
    index = line.find('\t')#以tab键为分割  
    key = line[:index]  
    value = line[index:]  
    txtDict[key] = value#加入字典  
dicFile.close()  
##查找字典  
srcFile = open('train1.txt', 'r')#要匹配的key  
destFile = open('match.txt', 'w')#符合字典的写入里面  
while True:  
    line = srcFile.readline()  
    if line == '':  
        break  
    index = line.find(' ')  
    key = line[:index]  
    if txtDict.has_key(key):      
        destFile.write(key)  
        destFile.write(txtDict[key])         
    else:  
        badFile.write(key)  
        badFile.write('\n')  
print '全部完成!'  
destFile.close()  
srcFile.close()  

来源:https://blog.csdn.net/rooki_men/article/details/52088300

标签:Python,txt,字典,查询
0
投稿

猜你喜欢

  • Python Pandas批量读取csv文件到dataframe的方法

    2022-12-15 17:05:03
  • Mootools 1.2教程(5)——事件处理

    2008-11-19 16:33:00
  • python通过nmap扫描在线设备并尝试AAA登录(实例代码)

    2021-08-06 23:23:42
  • Python pickle模块常用方法代码实例

    2023-12-25 03:09:16
  • python爬虫之urllib,伪装,超时设置,异常处理的方法

    2022-07-23 23:47:10
  • python中subplot大小的设置步骤

    2021-07-30 08:59:37
  • 显示某日期所在星期的所有日期asp代码

    2008-06-01 16:05:00
  • MySQL数据库对dvbbs.php全文搜索的完全分析

    2010-06-11 13:25:00
  • PHP爬虫框架盘点

    2023-06-10 07:10:12
  • python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据示例

    2022-12-24 23:49:30
  • 手把手教你python实现SVM算法

    2022-04-22 09:29:06
  • python在命令行下使用google翻译(带语音)

    2023-06-02 13:47:17
  • Python实现简单状态框架的方法

    2022-08-20 14:13:44
  • python爬虫headers设置后无效的解决方法

    2021-09-04 00:55:17
  • python jieba库的基本使用

    2022-10-15 23:01:16
  • 将ASP记录集输出成n列的表格形式显示的方法

    2011-04-08 10:51:00
  • SQL Server各种日期计算方法

    2008-09-11 21:47:00
  • python实现图像最近邻插值

    2023-02-01 00:03:34
  • JS实现css边框样式设置工具

    2008-05-25 16:22:00
  • Python逐行读取文件中内容的简单方法

    2023-03-02 16:01:09
  • asp之家 网络编程 m.aspxhome.com