python:将数据从txt文件中读取并保存到字典中

您所在的位置:网站首页 python中如何创建一个空字典的数据库文件类型 python:将数据从txt文件中读取并保存到字典中

python:将数据从txt文件中读取并保存到字典中

#python:将数据从txt文件中读取并保存到字典中| 来源: 网络整理| 查看: 265

文件lexicon.txt是一些英文单词的发音词典文件:文件的每一行对应一个词条,每一行的第一列对应词本身,后面列对应该单词的发音音素序列。编写一个函数,从lexicon.txt将相关内容读出,放入一个字典结构中,返回该字典结构,并测试peppers和piper的音素序列是否正确。

txt文件: a ah a ey cat k ae t of ah v peck p eh k peppers p eh p er z peter p iy t er picked p ih k t pickled p ih k ah l d piper p ay p er the dh ah the dh iy where’s w eh r z

```python def txt_read(files): txt_dict = {} fopen = open(files) for line in fopen.readlines(): line = str(line).replace("\n","") #注意,必须是双引号,找了大半个小时,发现是这个问题。。 txt_dict[line.split(' ',1)[0]] = line.split(' ',1)[1] #split()函数用法,逗号前面是以什么来分割,后面是分割成n+1个部分,且以数组形式从0开始 #初学python,感觉这样表达会理解一点。。 fopen.close() return txt_dict txt_dict = txt_read('lexicon.txt') print(txt_dict)

差不多了

输出结果: {'a': 'ey', 'cat': 'k ae t', 'of': 'ah v', 'peck': 'p eh k', 'peppers': 'p eh p er z', 'peter': 'p iy t er', 'picked': 'p ih k t', 'pickled': 'p ih k ah l d', 'piper': 'p ay p er', 'the': 'dh iy', "where's": 'w eh r z'}


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3