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

  1. 文件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'}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值