2017-06-16 64 views
1

我想要一个带有所有文本的文本文件,它在程序中表示,以便将我的程序翻译成另一种语言。我可以使用普通列表,但是当查看代码时很难看到哪些文本将被表示。将文件转换为字典

文本文件:

here is the text represented in the running program 
inside the code you cant say whats written right here 

代码:

language_file = open("file.txt", "r", encoding="utf-8") 
language_list = storage_file.readlines() 
print(language_list[1]) 

我希望你能理解与^ 而不是使用一个列表的我的问题,我想用一本字典。而该文件,那么应该是这个样子:

"some_shortcut_to_remind_me_whats_happening": "Text in another language" 
"another_shortcut": "Now I know whats written right here" 

的代码,然后可能看起来像这样:

print(language_dict["another_shortcut"]) 

但我不知道怎么去解释了文本文件的

+0

你想第一行作为关键和第二行作为值等? –

+0

可能的重复:https://stackoverflow.com/questions/4803999/python-file-to-dictionary – mimre

回答

2

为什么不只是将文件保存在json中?它仍然易于阅读,你可以有多个语言在一个文件中太:

例子:

File.json包含:

{ 
    "en": 
    { 
     "some_shortcut_to_remind_me_whats_happening": "Text in another language", 
     "another_shortcut": "Now I know whats written right here" 
    } 
} 

而且你的代码将是这样的:

import json 

with open("file.json", "r") as f: 
    json = json.load(f) 

print(json["en"]["some_shortcut_to_remind_me_whats_happening"]) 
+1

这是正确的答案。 JSON的存在是有原因的。小改进就是将'open(“file.json”,“r”)作为f:\ n \ tjson = json.load(f)'。 – pzp

+0

谢谢@pzp,修正了:) – ciprianoss

0

如果您不想使用外部库并将文件格式设置如下:

key1: value1 
key2: value2 
..... 

您可以使用:

with open(filename, 'r') as f: 
    my_dict = dict((key, value.strip()) 
        for key, value in (line.split(':') for line in f)) 
0

你描述什么看起来像一个CSV文件,其中分隔符是:并使用"作为引用(默认值)。你可以很容易地建立自己的查找表的方式:

language_dict = {} 
with open("file.txt", "r", encoding="utf-8", newline='') as language_file: 
    reader = csv.reader(language_file, delimiter=':', skipinitialspace=True) 
    for row in reader: 
     language_dict[row[0]] = row[1] 

注意:此语法只适用于Python3,不幸的是,用于CSV文件的开口Python2和Python3不同。在Python2第一行将是:

with open("file.txt", "rb") as language_file: