[英]how to split a string containing more than one list? 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)]
正如另一個問題所建議的那樣: 問題我嘗試使用ast.literal_eval()
但我收到此錯誤:
return compile(source, filename, mode, flags, File "<unknown>", line 1
['Gore'
^
SyntaxError: unexpected EOF while parsing
Output 預期:
["hello test", "C", "['Gore', 'Family']", "3.4", "Actor", "['Cesar', 'Mile']", "1"]
如果它有幫助,我在只有 1 個列表時嘗試使用相同的代碼,並且它完美地拆分了它。
任何幫助表示贊賞:)
s = "hello test, C, ['Gore', 'Family'], 3.4, Actor, ['Cesar', 'Mile'], 1"
splitted = re.split(r', (?!\')', s)
只有在狹縫表達式后沒有單引號'
時,這才會在,
(逗號和空格)上拆分行。 有關前瞻語法的更多信息: https://docs.python.org/3/library/re.html#index-21
Output:
['hello test',
'C',
"['Gore', 'Family']",
'3.4',
'Actor',
"['Cesar', 'Mile']",
'1']
我認為它會幫助你解決問題。
Basetext = open("LAB3.txt", "r")
listfortext = []
for line in Basetext:
listfortext.append(line.split())
Basetext.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.