簡體   English   中英

讀取文件並將其拆分為字典

[英]Read & split file into dictionary

我有一個文件,其數據如下:

1 [0,1, 4, 89]     
2 [3, 56, 6]     
3 [3,4,0]

等等。

我想讀取此文件以逐行訪問腳本中的數據,因此嘗試讀取文件並將其存儲在字典中:

dictionary = {}

with open('file.txt') as f:
    for line in f:
        nb, list = line.split(' ')
        dictionary[nb] = list 

然后,我將執行以下操作:

for e in dictionary:
    etc.

我有這個錯誤:

too many values to unpack

因為我不知道如何處理列表中的第二個split元素。

還有其他方法可以輕松訪問和使用任何輸入文件嗎?

首先,可以設置str.split()maxsplit參數。 從文檔中:

str.split(sep=None, maxsplit=-1)

使用sep作為分隔符字符串,返回字符串中單詞的列表。 如果指定了maxsplit,則最多完成maxsplit個分割(因此,列表最多包含maxsplit+1元素)。 如果未指定maxsplit或-1 ,則分割數沒有限制(已進行所有可能的分割)。

演示:

>>> s = '1 [0,1, 4, 89]'
>>> s.split(' ', 1)
['1', '[0,1, 4, 89]']
>>> s.split(' ')
['1', '[0,1,', '4,', '89]']

>>> s.split(' ')[1]
'[0,1,'
>>> s.split(' ', 1)[1]
'[0,1, 4, 89]'

然后,您需要將list字符串轉換為真實列表 我建議使用ast.literal_eval() 從文檔中:

ast.literal_eval(node_or_string)

安全地評估表達式節點或包含Python文字或容器顯示的字符串。 提供的字符串或節點只能由以下Python文字結構組成:字符串,字節,數字,元組,列表,字典,集合,布爾值和None

例如:

>>> import ast
>>> s = '1 [0,1, 4, 89]'
>>> s.split(' ', 1)[1]
'[0,1, 4, 89]'
>>> ast.literal_eval(s.split(' ', 1)[1])
[0, 1, 4, 89]
>>> type(ast.literal_eval(s.split(' ', 1)[1]))
<class 'list'>
>>> type(s.split(' ', 1)[1])
<class 'str'>

如果需要刪除字符串后的\\n ,只需使用str.strip() 從文檔中:

str.strip([chars])

返回刪除前導和尾隨字符的字符串的副本。 chars參數是一個字符串,指定要刪除的字符集。 如果省略或為None,則chars參數默認為刪除空格。

像這樣使用它:

>>> '   1 [0,1, 4, 89]   '.strip()
'1 [0,1, 4, 89]'
>>> '1 [0,1, 4, 89]\n'.strip()
'1 [0,1, 4, 89]'
>>> 

它會刪除字符串前后的str.lstrip()符,換行符和空格。如果只想刪除字符串前后的空格,換行符,請查看str.lstrip()str.rstrip()


因此,您可以這樣編寫代碼:

import ast
dictionary = {}

with open('file.txt') as f:
    for line in f:
        key, value = line.strip().split(1)
        dictionary[key] = value

如果希望dictionary的鍵為int對象,只需使用int()函數將其轉換為:

import ast
dictionary = {}

with open('file.txt') as f:
    for line in f:
        key, value = line.strip().split(' ', 1)
        dictionary[int(key)] = value

這樣可以嗎?

import ast
d = dict()
with open('file.txt') as f:
    for line in f:
        k, l = line.split(' ', 1)
        d[k] = ast.literal_eval(l)

print(d)

它產生

{'3': [3, 4, 0], '1': [0, 1, 4, 89], '2': [3, 56, 6]}

如果您希望鍵是整數而不是字符串,請執行

d[int(k)] = ast.literal_eval(l)

使用maxsplit參數和ast.literal_eval()

import ast
dictionary = {}

with open('file.txt') as f:
    for line in f:
        nb, l = line.split(maxsplit=1)
        dictionary[nb] = ast.literal_eval(l)

請注意,我已經將list的名稱更改為不會掩蓋內置函數list() ,並使用了所有空白的默認定界符。

要進行保存評估,請使用ast.literal_eval

from ast import literal_eval

data = {}
with open('file.txt') as fobj:
    for line in fobj:
        key, rest = line.split(None, 1)
        data[key] = literal_eval(rest)


>>> data
{'1': [0, 1, 4, 89], '2': [3, 56, 6], '3': [3, 4, 0]}

從文檔:

 ast.literal_eval(node_or_string) 

這可用於安全地評估包含來自不受信任來源的Python值的字符串,而無需自己解析值。

暫無
暫無

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

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