[英]Python(3.x) - Opening File and Removing the Quotation Marks when reading file
我目前正在嘗試加載一個.txt文件,該文件中包含以下內容:
['胸',['板凳','傾斜'],[2,1],[10,10],[10,20,10]],'胸',['下降'],[1], [1],[10]
當我加載文件時,讀取文件上的信息並將其存儲在名為content
的變量中:
self.file_name = filedialog.askopenfilename()
if self.file_name is None:
return
with open(self.file_name) as f:
content = f.read().splitlines()
當我打印內容時:
print(content)
我得到以下輸出:
["['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10]"]
問題是打印時帶有引號。 反正還有擺脫“”的地方嗎? 原因是因為它是一個二維列表,並且print([0][1])
我得到的結果是'而不是chest
如果您的內容包含表示正確的python文字代碼的語法,則可以將其直接解析為python數據:
content = ["['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10]"]
import ast
a_tuple = ast.literal_eval(content[0])
print(a_tuple)
產生一個包含參數字符串的連音符:
(['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10])
print(content[0])
content
變量包含單個字符串的數組。 當您執行print(content[0][1])
,您打印了字符串的第二個字符。 在打印字符串時,不顯示外部引號,但是在打印數組時,顯示外部引號(因此您可以看到每個字符串的開始和結束位置)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.