如何拆分包含多个列表的字符串?python

2024-06-11 10:41:10 发布

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

嗨,我有麻烦,而读取一个文件,并试图分裂一个字符串,有2个列表。你知道吗

文件文本中有以下字符串:

BaseDeDatos.txt文件:

hello test, C, ['Gore', 'Family'], 3.4, Actor, ['Cesar', 'Mile'], 1

代码:

with open('BaseDeDatos.txt', 'r') as data:
        peli = data.readlines()[int(modificar_peli)-1]
        selec_final = [ast.literal_eval(i) if i.startswith('[') else int(i) if re.findall('^\\d+$', i) else i for i in re.split(',\s*', peli)]

正如另一个问题所暗示的:question我尝试使用ast.literal_eval()但是我得到了这个错误:

return compile(source, filename, mode, flags,  File "<unknown>", line 1
    ['Gore'
          ^
SyntaxError: unexpected EOF while parsing

预期输出:

["hello test", "C", "['Gore', 'Family']", "3.4", "Actor", "['Cesar', 'Mile']", "1"] 

如果有帮助的话,当我只有一个列表时,我尝试使用相同的代码,它将它完美地拆分。你知道吗

感谢您的帮助:)


Tags: 文件字符串代码testtxthello列表data
2条回答

我想这对你的问题有帮助。你知道吗

Basetext = open("LAB3.txt", "r")
listfortext = []
for line in Basetext:
    listfortext.append(line.split())
Basetext.close()
s = "hello test, C, ['Gore', 'Family'], 3.4, Actor, ['Cesar', 'Mile'], 1"

splitted = re.split(r', (?!\')', s)

只有在slit表达式后面没有单引号'时,这才会拆分,(逗号和空格)上的行。有关lookahead语法的详细信息:https://docs.python.org/3/library/re.html#index-21

输出:

['hello test',
 'C',
 "['Gore', 'Family']",
 '3.4',
 'Actor',
 "['Cesar', 'Mile']",
 '1']

相关问题 更多 >