使用文件内容蟒
答
试试这个:
with open('test.txt','r') as file:
content = file.readlines()
my_dict = {}
for line in content:
split = line.split(':')
my_dict[split[0]] = split[1]
input = raw_input("Choose a letter")
if input in my_dict:
print my_dict[input]
这将是更好地使用从正宗OrderedDict,因为默认字典有没有一个确切的秩序。
+0
有没有可能不使用字典? –
+0
当然。这里的列表方式: 开放( 'test.txt的', 'R')的文件: \t含量= file.readlines() 输入的raw_input =( '选择一个字母:') 在内容线路: \t split = line.split(':') \t if input == split [0]: \t \t print split [1] – echo
答
请尝试下面的解决方案,如果用户输入的任何字母表不存在于您的txt文件中,您可以提供一条有用的信息。
with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj:
content = file_obj.readlines()
sample_dict = {}
for value in content:
sample_dict[value.split(':')[0]] = value.split(':')[1]
input_key = raw_input("Please enter an alphabet: \n")
print sample_dict.get(input_key, "No value exists")
可能使用字典存储地图。 – heLomaN