在 Python 中将 txt 文件转换为字典
nlp 645
原文标题 :Transform a txt file to dictionary in Python
假设存在以下文本文件 (lemma_es.txt):
昏迷
来了
来者不善
来人科曼
第一列代表第二列的引理,第二列代表变形词。
我正在尝试制作一个字典,其中键是第二个单词中的单词,值是第一列中的单词。
我需要的输出:
{‘coma’: ‘comer’, ‘comais’: ‘comer’, ‘comamos’: ‘comer’, ‘coman’: ‘comer’ … }
谢谢你们!
回复
我来回复-
Airã Carvalho da Silva 评论
我想你可以试试这个:
myfile = open("lemma_es.txt", 'r') data_dict = {} for line in myfile: k, v = line.strip().split() data_dict[k.strip()] = v.strip() myfile.close() print(' text file to dictionary =\n ',data_dict)
2年前 -
Ajay Pyatha 评论
word_dict={} with open("lemma_es.txt","r") as filehandle: for line in filehandle.readlines(): word_dict[line.split()[-1]]=line.split()[0]
读取 txt 文件并使用 readlines 读取每一行。拆分行并仅使用列表的第二个值作为键。
2年前 -
mozway 评论
IIUC,您可以使用:
with open('lemma_es.txt') as f: d = dict(reversed(l.strip().split()) for l in f)
输出:
{'coma': 'comer', 'comais': 'comer', 'comamos': 'comer', 'coman': 'comer'}
注意。请注意,第二个单词必须是唯一的
2年前