我正在撰寫代碼,在其中生成一些規則。下面是我的代碼的最后幾行:
for _,i in enumerate(range(no_of_label 1)):
if _ in temp_key:
rule_pro.append(temp_lab[_])
elif _ == no_of_label:
rule_pro.append(class_)
else:
rule_pro.append("*")
print(*rule_pro, sep = ",")
現在在代碼之間,我也在標準輸出中生成 3-4 個輸出。但是我需要將其寫入rule_pro
一個檔案中,例如Outputfile
. 每當我試圖將這個東西從標準輸出復制到那個檔案時,標準輸出中的所有東西都會被復制,但我只需要把它放到rule_pro
一個檔案中。我怎樣才能做到這一點?請幫忙!
編輯_1:
with open('Output_rule_c45_rise_format', 'w') as file_handler:
file_handler.write(str(rule_pro))
這是有效的,但我沒有得到我想要的格式,我正在stdout
使用print(*rule_pro, sep = ",")
.
的stdout
輸出就像:
*,*,1,*,0
*,*,2,2,1
*,*,*,3,1
*,*,*,4,2
*,*,3,*,2
但是修改代碼,在那個輸出檔案中我得到了這樣的:
['*', '*', '1', '*', '0']['*', '*', '2', '2', '1']['*', '*', '*', '3', '1']['*', '*', '*', '4', '2']['*', '*', '3', '*', '2']
但我不需要這些第三個括號,我需要在單獨的行中列印它們。我需要做哪些改變?
編輯_2:
現在我正在做:
for rule in rule_pro:
#rule_line = ','.join(map(str, rule))
#rule_line = "\n".join(map(str, rule))
rule_line = "\n".join(map(str, rule)) '\n'
file_handler.write(rule_line)
但這使輸出為:
*
*
1
*
0
*
*
2
2
1
*
*
*
3
1
*
*
*
4
2
*
*
3
*
2
uj5u.com熱心網友回復:
編輯后 1。
您似乎正在將串列的字串表示形式寫入檔案。您應該首先嘗試從串列中創建一個字串。
下面的代碼應該可以幫助您轉換它。它遍歷串列并獲取每個專案。在這種情況下,您似乎有一個包含串列的串列,因此您的專案是一個串列。在此之后,通過使用規則中的每個專案(這是一個串列)連接/創建一個字串,然后將其保存在一個變數中。rule_line 是一個字串,可以寫入檔案。添加了一個換行符,因此它位于檔案的下一行。
參考
with open('Output_rule_c45_rise_format', 'w') as file_handler:
for rule in rule_pro:
rule_line = ','.join(map(str, rule)) '\n'
file_handler.write(rule_line)
假設 rule_pro 是一個串列串列,這應該可以作業。
編輯后2。
IndentationError 是空格和/或制表符的一致性問題。嘗試在代碼中僅使用制表符或僅使用 4 個空格。不要在縮進中混用制表符和空格。
如果 rule_pro 是一個帶有串列的串列,它看起來像這樣。
rule_pro = [['*', '*', '1', '*', '0'],
['*', '*', '2', '2', '1'],
['*', '*', '*', '3', '1'],
['*', '*', '*', '4', '2'],
['*', '*', '3', '*', '2']]
您可以通過嘗試以下操作來檢查您的線路是否正確:
for rule in rule_pro:
rule_line = ','.join(map(str, rule)) '\n'
print(rule_line)
請檢查您的 rule_pro 串列是否與我想到的 rule_pro 相似。
uj5u.com熱心網友回復:
檢查檔案: Python 檔案處理:https : //www.w3schools.com/python/python_file_handling.asp
Python檔案打開:https : //www.w3schools.com/python/python_file_open.asp
Python 檔案寫入:https : //www.w3schools.com/python/python_file_write.asp
Python 檔案洗掉:https : //www.w3schools.com/python/python_file_remove.asp
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370683.html