简体   繁体   English

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

[英]how to split a string containing more than one list? python

Hi Im having trouble while reading a file and trying to split a string that has 2 lists.嗨,我在读取文件并尝试拆分具有 2 个列表的字符串时遇到问题。

I have this string in the file text:我在文件文本中有这个字符串:

BaseDeDatos.txt: BaseDeDatos.txt:

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

Code:代码:

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)]

As suggested from another question: question I tried using ast.literal_eval() but im getting this error:正如另一个问题所建议的那样: 问题我尝试使用ast.literal_eval()但我收到此错误:

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

Output Expected: Output 预期:

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

If it helps I tried using the same code when I had only 1 list and it split it perfectly.如果它有帮助,我在只有 1 个列表时尝试使用相同的代码,并且它完美地拆分了它。

Any help is appreciated:)任何帮助表示赞赏:)

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

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

This will split the line on , (comma and space) only if there is no single-quote ' after slit expression.只有在狭缝表达式后没有单引号'时,这才会在, (逗号和空格)上拆分行。 More about lookahead syntax: https://docs.python.org/3/library/re.html#index-21有关前瞻语法的更多信息: https://docs.python.org/3/library/re.html#index-21

Output: Output:

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

I think it will help your problem.我认为它会帮助你解决问题。

Basetext = open("LAB3.txt", "r")
listfortext = []
for line in Basetext:
    listfortext.append(line.split())
Basetext.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM