[英]Read a list of strings from text file and remove the extra quotes
在我的文本文件中,有一個字符串列表,如下所示:
['', '"0=SYSEV,1=APPEV,2:3=VECEV"', '"ASEN"+$y', '"FALSE"', '"G"+$x+"ARBCFG"', '"G"+$x+"ARBPR"', '"HUGO:SECURE"', '"Internal"', '"SERIAL0:TRANSMIT"', '$fpi_mem_range', '$fpi_to_sri_base', '$fpi_to_sri_range', '$sx_fpi_base', '$sx_fpi_range', '$sx_sri_dest', '$trignum_g-1', '$x!=0', '$x!=1', '$x==1', '0', '0x0', '0x00', '0x0000', '0x00000000', '0x00000FFFF', '0x0000FFFF', '0x0D', '0x10', '0x1000', '0x10000000', '0x11001111', '0x11111100', '0xffc', '0xffffffff', '1', '1 clock cycle for generating the MSB', '10', '100', '101', '102', '103', '104', '115', '1156', '116', '117', '118', '1188', '119', '1192', '1196', '12', '120']
此列表使用以下代碼寫在文本文件中:
thefile = open('test.txt', 'w')
for item in thelist:
thefile.write("%s\n" % item)
我想再次閱讀清單。 所以我正在使用此代碼:
with open('test.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
我獲得的列表是正確的,但提取的字符串包含我要刪除的多余引號。 這是我獲得的清單:
['','"0=SYSEV,1=APPEV,2:3=VECEV"','"ASEN"+$y','"FALSE"',....,'0x0000FFFF']
為了刪除多余的引號,我使用了ast.literaleval(),但是出現了這個錯誤:
File "/home/ubuntu/anaconda3/lib/python3.6/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
"ASEN"+$y
^
SyntaxError: unexpected EOF while parsing
似乎它刪除了列表中所有元素的單引號,甚至是我們不需要刪除其引號的單引號。 還有更好的主意嗎?
一個可能的解決方案是使用re.sub刪除所有雙引號字符。 實際上,這是通過使用正則表達式匹配雙引號字符並替換為空字符來完成的。
import re
thelist = ['','"0=SYSEV,1=APPEV,2:3=VECEV"','"ASEN"+$y','"FALSE"','0x0000FFFF']
newlist = [];
for item in thelist:
newlist.append(re.sub('["]','',item))
newlist
將包含列表中的元素, thelist
帶雙引號。
編輯。
您還可以使用str.replace
方法來提高性能,如下面的zwer所指出的。
for item in thelist:
newlist.append(item.replace('"',''))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.