如何将此文本文件转换为字典?(PYTHON)
我有一个.txt文件,内容如下:如何将此文本文件转换为字典?(PYTHON),python,file,dictionary,object,methods,Python,File,Dictionary,Object,Methods,我有一个.txt文件,内容如下: Areca Palm 2018-11-03 18:21:26 Tropical/sub-Tropical plant Leathery leaves, mid to dark green Moist and well-draining soil Semi-shade/full shade light requirements Water only when top 2 inches of soil is dry Intolerant to root rot Pr
Areca Palm
2018-11-03 18:21:26
Tropical/sub-Tropical plant
Leathery leaves, mid to dark green
Moist and well-draining soil
Semi-shade/full shade light requirements
Water only when top 2 inches of soil is dry
Intolerant to root rot
Propagate by cuttings in water
Canary Date Palm
2018-11-05 10:12:15
Semi-shade, full sun
Dark green leathery leaves
Like lots of water,but soil cannot be water-logged
Like to be root bound in pot
我想将这些.txt文件转换为python上的dictionary,输出应该如下所示:
d = {'Areca Palm': ('2018-11-03 18:21:26', 'Tropical/sub-Tropical plant', 'Leathery leaves, mid to dark green', 'Moist and well-draining soil'..etc 'Canary Date Palm': ('2018-11-05 10:12:15', 'Semi-shade, full sun'...)
如何执行此操作?以下代码显示了一种执行此操作的方法,使用非常简单的两状态机读取文件:
with open("data.in") as inFile:
# Initialise dictionary and simple state machine.
afterBlank = True
myDict = {}
# Process each line in turn.
for line in inFile.readlines():
line = line.strip()
if afterBlank:
# First non-blank after blank (or at file start) is key
# (blanks after blanks are ignored).
if line != "":
key = line
myDict[key] = []
afterBlank = False
else:
# Subsequent non-blanks are additional lines for key
# (blank after non-blank switches state).
if line != "":
myDict[key].append(line)
else:
afterBlank = True
# Dictionary holds lists, make into tuples if desired.
for key in myDict.keys():
myDict[key] = tuple(myDict[key])
import pprint
pprint.pprint(myDict)
使用输入数据给出输出(使用pprint
输出,使其比标准Pythonprint
更可读):
通过编写函数,许多解析问题都大大简化了 处理文件并一次生成一个有意义的部分。 通常,这部分所需的逻辑非常简单。和 它保持简单,因为该函数与其他函数无关 关于更大问题的详细信息 然后,这一步骤简化了下游代码,重点是解构 一次一个有意义的部分。这一部分可以忽略更大的文件问题——也可以 保持简单 举例说明:
import sys
def get_paragraphs(path):
par = []
with open(path) as fh: # The basic pattern tends to repeat:
for line in fh:
line = line.rstrip()
if line: # Store lines you want.
par.append(line)
elif par: # Yield prior batch.
yield par
par = []
if par: # Don't forget the last one.
yield par
path = sys.argv[1]
d = {
p[0] : tuple(p[1:])
for p in get_paragraphs(path)
}
import sys
def get_paragraphs(path):
par = []
with open(path) as fh: # The basic pattern tends to repeat:
for line in fh:
line = line.rstrip()
if line: # Store lines you want.
par.append(line)
elif par: # Yield prior batch.
yield par
par = []
if par: # Don't forget the last one.
yield par
path = sys.argv[1]
d = {
p[0] : tuple(p[1:])
for p in get_paragraphs(path)
}