我有一个由两列组成的文件,即
1 a
2 b
3 c
我希望将这个文件读入一个字典中,使得第一列为键,第二列为值,也就是说:
d = {1:'a', 2:'b', 3:'c'}
这个文件很小,所以效率不是问题。
我有一个由两列组成的文件,即
1 a
2 b
3 c
我希望将这个文件读入一个字典中,使得第一列为键,第二列为值,也就是说:
d = {1:'a', 2:'b', 3:'c'}
这个文件很小,所以效率不是问题。
d = {}
with open("file.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
这将把键留作字符串:
with open('infile.txt') as f:
d = dict(x.rstrip().split(None, 1) for x in f)
dict([line.split() for line in f])
就足够了。 - user225312dict([x.rstrip().split(None, 1) for x in f])
而不是dict(x.rstrip().split(None, 1) for x in f)
。对于那些有同样疑问的人,前者是生成器表达式而不是列表推导式,这在这里得到了解释:https://www.python.org/dev/peps/pep-0289(PEP-289)。学到了新东西! - peaxol你也可以使用字典推导式,例如:
with open("infile.txt") as f:
d = {int(k): v for line in f for (k, v) in [line.strip().split(None, 1)]}
def get_pair(line):
key, sep, value = line.strip().partition(" ")
return int(key), value
with open("file.txt") as fd:
d = dict(get_pair(line) for line in fd)
partition
和with
语句? - SilentGhostpartition
更快,专门为此目的创建。 - SilentGhostwith
是确保它关闭的简单方法。 - SilentGhoststrip
。 - SilentGhost通过字典解析
d = { line.split()[0] : line.split()[1] for line in open("file.txt") }
使用pandas
import pandas as pd
d = pd.read_csv("file.txt", delimiter=" ", header = None).to_dict()[0]
大多数存储字典的方法使用JSON、Pickle或逐行读取。只要您不在Python之外编辑字典,这种简单方法就足以处理复杂的字典。虽然对于较大的字典,Pickle会更好。
x = {1:'a', 2:'b', 3:'c'}
f = 'file.txt'
print(x, file=open(f,'w')) # file.txt >>> {1:'a', 2:'b', 3:'c'}
y = eval(open(f,'r').read())
print(x==y) # >>> True
依我之见,更pythonic的做法是使用生成器(可能需要2.7+版本):
with open('infile.txt') as fd:
pairs = (line.split(None) for line in fd)
res = {int(pair[0]):pair[1] for pair in pairs if len(pair) == 2 and pair[0].isdigit()}
这也将过滤掉不以整数开头或不包含恰好两个项目的行
d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
输入FILE = 文件路径,SEP = 键值分隔符字符
虽然不是最优雅或最有效的方法,但仍然非常有趣 :)
我有一个需求,需要从文本文件中获取值并将其用作键值对。我的文本文件中的内容是key = value,因此我使用了分割方法,并将分隔符设置为“=”,然后编写了以下代码:
d = {}
file = open("filename.txt")
for x in file:
f = x.split("=")
d.update({f[0].strip(): f[1].strip()})
=
替换为
来回答这个问题呢? - Prunus Persicaimport re
my_file = open('file.txt','r')
d = {}
for i in my_file:
g = re.search(r'(\d+)\s+(.*)', i) # glob line containing an int and a string
d[int(g.group(1))] = g.group(2)
split()
函数几乎不会悄无声息地工作。 - VGE
with
来处理文件清理。当你离开代码块时(无论是正常执行流还是出现异常),文件都会自动关闭。你可以在这里阅读更多关于 Python 上下文管理器的内容:http://effbot.org/zone/python-with-statement.htm - Vlad Hfor line in open("file.txt"):
做完清理工作。如果f是一个本地值,那么当范围丢失时f会被释放。这个语句有用的唯一情况是长函数(不利于质量),或者您使用全局变量。 - VGEfor line in open('file.txt')
的清理方式并不相同。不是所有的Python实现都一样。with
保证当退出块时文件将被关闭。当for
行完成时,可能会调用close
。在CPython
中,确实会调用,但像IronPython
这样的版本具有懒惰的垃圾收集器。 - Mark Tolonen