Python 如何将文件中的一个字符作为键读入字典,然后将接下来的n个字符作为其值?
假设我们有这样一个.txt文件(都在一行上):Python 如何将文件中的一个字符作为键读入字典,然后将接下来的n个字符作为其值?,python,file,dictionary,file-read,Python,File,Dictionary,File Read,假设我们有这样一个.txt文件(都在一行上): A2.)43@|@C3::# 因此,我们希望“A”作为值的键“…”),而“4”作为值的键“@|@”等等。。键后的数字告诉我们要读取多少个字符作为值,键后的字符是字典中下一项的键 我一直在努力写循环。我认为我们可能希望使用for循环遍历文件的长度。但我真的不知道该怎么做。这对我来说很有效 stringText = "A2.)43@|@C3::#" i=0 myDictionary = {} while True: try:
A2.)43@|@C3::#
因此,我们希望“A”作为值的键“…”),而“4”作为值的键“@|@”等等。。键后的数字告诉我们要读取多少个字符作为值,键后的字符是字典中下一项的键
我一直在努力写循环。我认为我们可能希望使用for循环遍历文件的长度。但我真的不知道该怎么做。这对我来说很有效
stringText = "A2.)43@|@C3::#"
i=0
myDictionary = {}
while True:
try:
#First we grab the key character using i
keyCharacter = stringText[i]
#Then we grab the next character which will tell us how many characters they value will have
# We also convert it to integer for future use
valueLength = int(stringText[i+1])
#Then we grab the value by slicing the string
valueCharacters = stringText[i+2:i+2+valueLength]
#We add this to the dictionary
myDictionary[keyCharacter] = valueCharacters
#We update i to continue where we left off
i = i+2+valueLength
except IndexError:
break
print myDictionary
除了“try and except”之外,您还可以看到该字符串的长度和do以及if语句,以便在i大于字符串长度时中断循环。A
while
loop更好,这样您就可以任意增加索引变量(或者改为检查文件结尾)一次处理一个值的所有字符。这里有一个提示:去上课并阅读笔记。为什么要跳过“4”后面的“3”字符?