如何将文本文件转换为python字典
如果我有一个包含以下文本的文本文件:如何将文本文件转换为python字典,python,dictionary,text-files,Python,Dictionary,Text Files,如果我有一个包含以下文本的文本文件: string, float string 2, float 2 string 3, float 3 ... and so on 如何将其转换为python词典 最终,我希望我所有的字符串都成为键,所有的浮点数都成为值 我试着把它做成一套,但我无法达到我想要的效果 我还尝试了以下代码,因为我看到另一篇文章也有类似的问题,给了我这个解决方案。然而,我无法让它打印任何东西 m={} for line in file: x = line.re
string, float
string 2, float 2
string 3, float 3
... and so on
如何将其转换为python词典
最终,我希望我所有的字符串都成为键,所有的浮点数都成为值
我试着把它做成一套,但我无法达到我想要的效果
我还尝试了以下代码,因为我看到另一篇文章也有类似的问题,给了我这个解决方案。然而,我无法让它打印任何东西
m={}
for line in file:
x = line.replace(",","") # remove comma if present
y=x.split(':') #split key and value
m[y[0]] = y[1]
非常感谢。如果文本文件中的每一行的格式都与示例中的格式完全相同,那么我将这样做:
m = {}
for line in file:
comma = line.find(", ") # returns the index of where the comma is
s = line[:comma]
f = line[comma+1:]
m[s] = str.strip(f) # str.strip() removes the extra spaces
你需要做更多的研究。不要偷懒
m = {}
for line in file:
(key, value) = line.split(',') # split into two parts
m[key] = value.strip('\n') # remove the line break and append to dictionary
# output
# {'string1': ' 10', 'string2': ' 11'}
无法打印任何内容您是否也可以发布输出?与预期输出对比这是否回答了您的问题?