1

如何从只有字符串内容的文本文件中简单地填充 Python 3.2 中的字典?

我是 Python 新手,我正在尝试从仅包含两列的文本文件构建字典,如下所示:

First_column        second_column
katab           perfective active 
kutib                 perfective passive 
?aktub            imperfective active 
?uktab           imperfective passive 
ka:tib               participle active 
maktu:b         participle passive
The text file contains thousands of lines. 

1.我希望first_column下的单词作为“keys”,second_column下的单词作为“values”,例如

dict = {‘katab’ : ‘perfective_active’, ‘kutib’ : ‘perfective_passive’}

请注意,文本文件包含大量格式和转义字符,例如 ''、'\n' 和 '\t'。所以我不希望这些字符出现在字典中。

  1. 如何将生成的 dict 写入文件,然后将其导入 Python shell 并搜索给定的键?

这是打印到文本文件的代码:

        import sys
        sys.stdout = open("/home/mohammed/seminar/awzan", "a")
        print(perfective_active+"\t perfective_active \n")
        print(perfective_passive+"\t perfective_passive \n")
        print(imperfective_active+"\t imperfective_active \n")
        print(imperfective_passive+"\t imperfective_passive \n")
        print(participle_active+"\t participle_active \n")
        print(participle_passive+"\t participle_passive\n")
        sys.stdout.close()

我真的很感谢你的帮助!

4

2 回答 2

1

从磁盘文件中读取字典:

with open('inputfile.txt') as infile:
    d = dict(x.split(None, 1) for x in infile if x.strip())

要将字典写入磁盘文件:

with open('outputfile.txt', 'w') as outfile:
    outfile.write(''.join(' '.join(x) for x in d.iteritems()))

要搜索特定值:

stuff = d['bother']
于 2013-04-04T02:34:31.790 回答
0

如果您正在寻找拆分线路的方法。

>>> 'katab           perfective active'.split(None, 1)
['katab', 'perfective active']

将分割线存储到 dict

mydict = {}
for line in ifile:
    mydict.update(line.split(None, 1))

将字典存储到文件

尝试 python pickle 或 cpickle 模块

http://docs.python.org/2/library/pickle.html

于 2013-04-04T02:34:21.273 回答