簡體   English   中英

從文本文件中讀取(有點)非結構化數據以創建 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM