Прежде всего, вы можете установить аргумент maxsplit
str.split()
. Из документа:
str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1
elements). If maxsplit is not specified or -1
, then there is no limit on the number of splits (all possible splits are made).
Демо:
>>> 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]'
Затем вам нужно преобразовать строку списка в реальный список. Я бы рекомендовал использовать ast.literal_eval()
. Из документа:
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and 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])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.
использовать его как это:
>>> ' 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.rstrip()
.
Таким образом, вы можете написать код так:
import ast
dictionary = {}
with open('file.txt') as f:
for line in f:
key, value = line.strip().split(1)
dictionary[key] = value
Если вы хотите клавиши со dictionary
«s быть ИНТ объекты, просто использовать int()
функцию, чтобы преобразовать его нравится:
import ast
dictionary = {}
with open('file.txt') as f:
for line in f:
key, value = line.strip().split(' ', 1)
dictionary[int(key)] = value
взгляд на это, что вы получаете от spliting строку '[ '1', '[0,1,', '4', '89]]' – Netwave