从文本文件中读取(有点)非结构化数据以创建 Python 字典
Reading (somewhat) unstructured data from a text file to create Python Dictionary
我在名为 'user_table.txt'
的文本文件中有以下数据:
Jane - valentine4Me
Billy
Billy - slick987
Billy - monica1600Dress
Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
Charlotte - beutifulGIRL!
Christoper - chrisjohn
我正在尝试使用以下代码将此数据读入 Python 字典:
users = {}
with open("user_table.txt", 'r') as file:
for line in file:
line = line.strip()
# if there is no password
if '-' in line == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
print(users)
我收到以下错误:
ValueError: not enough values to unpack (expected 2, got 1)
这很可能是因为 Billy 的第一个实例没有 '-'
可以拆分。
如果是这种情况,解决此问题的最佳方法是什么?
谢谢!
你的条件有误,必须是:
for line in file:
line = line.strip()
# if there is no password
# if '-' not in line: <- another option
if ('-' in line) == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
或
for line in file:
line = line.strip()
# if there is password
if '-' in line:
key, value = line.split('-')
users[key] = value
我在名为 'user_table.txt'
的文本文件中有以下数据:
Jane - valentine4Me
Billy
Billy - slick987
Billy - monica1600Dress
Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
Charlotte - beutifulGIRL!
Christoper - chrisjohn
我正在尝试使用以下代码将此数据读入 Python 字典:
users = {}
with open("user_table.txt", 'r') as file:
for line in file:
line = line.strip()
# if there is no password
if '-' in line == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
print(users)
我收到以下错误:
ValueError: not enough values to unpack (expected 2, got 1)
这很可能是因为 Billy 的第一个实例没有 '-'
可以拆分。
如果是这种情况,解决此问题的最佳方法是什么?
谢谢!
你的条件有误,必须是:
for line in file:
line = line.strip()
# if there is no password
# if '-' not in line: <- another option
if ('-' in line) == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
或
for line in file:
line = line.strip()
# if there is password
if '-' in line:
key, value = line.split('-')
users[key] = value