所以我想出了如何將我的文本檔案制作成字典,但出現了問題。這是一個示例文本檔案:
豬:動物
狗:動物
貓:動物
車:東西
當我將其轉換為字典時,我得到:{"animal": ['pig','dog'], "animal" : ["cat"], "thing" : ['car']}
我需要貓和豬和狗一起去:{"animal": ["pig', 'dog', 'cat']} 但是由于文本檔案中冒號后沒有空格,我的程式無法識別關鍵還是一樣。
謝謝,需要任何幫助!
uj5u.com熱心網友回復:
您可以處理檔案并修復冒號空間問題:
file = open('your_text.txt', mode='r')
text = file.read()
text = re.sub(r':(\w)', r': \1', text)
file.close()
with open('your_text.txt', 'w') as file_out:
file_out.write(text)
uj5u.com熱心網友回復:
您可以使用該strip函式,它將洗掉字串開頭和結尾的所有空格。
uj5u.com熱心網友回復:
您可以洗掉 ':' 之后的所有空格。因此,每個值在 column(:) 之后都沒有空格。例如:
with open('test.txt', mode='r') as file:
text = file.read()
clean_text = re.sub(r':( ) ', ':', text)
with open('output.txt', 'w') as file_out:
file_out.write(clean_text)
所以對于輸入:
pig: animal
dog: animal
cat:animal
car: thing
輸出:
pig:animal
dog:animal
cat:animal
car:thing
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310908.html
上一篇:“07:37amGMT 5.30on10/11/2011”如何在python中將此字串轉換為日期時間
下一篇:從具有條件的資料框中采樣
