从文本文件中读取(某种程度上)非结构化数据以创建Python字典

2024-09-30 04:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在名为'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的第一个实例没有可拆分的'-'

如果是这样的话,解决这个问题的最佳方法是什么

谢谢


Tags: 数据keyintxtifvaluelinetable
1条回答
网友
1楼 · 发布于 2024-09-30 04:38:49

您的情况不正确,必须:

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

相关问题 更多 >

    热门问题