我的问题是如何将文本文件转换成字典 这是我的代码。而且我得到了错误ValueError:没有足够的值要解压(预期2,得到1)
filename = ("/users/Reza/Downloads/anyar.txt")
commands = {}
with open(filename) as fh:
for line in fh:
command, description = line.strip().split(' ', 1)
commands[command] = description.strip()
print(commands)
对不起我的英语。谢谢
答案 0 :(得分:1)
由于第一个数据行中没有空格,并且数据应该用/而不是空格分开,因此您收到错误消息。要获得预期的输出,您可以使用下面的示例代码。
import re
filename = ("input_file.txt")
has_header = True
count = 1
commands = {}
with open(filename) as fh:
for line in fh:
if has_header == True and count == 1:
count+=1
continue
nama, id, Jumlah = line.strip().split('/')
commands['nama'] = commands.get('nama','') + nama.split('.')[1] + ','
commands['id'] = commands.get('id','') + id.split(':')[1] + ','
commands['Jumlah'] = commands.get('Jumlah','') + Jumlah.split(':')[1] + ','
print(commands)
示例输出:
{'nama': 'Detergent ,Sabun Mandi ,Pasta gigi ,', 'id': 'B001 ,B002 ,B003 ,', 'Jumlah': '500,300,400,'}