[英]How do I write the contents of nested dictionaries to a file in a certain format?
[英]How do I write a text file with certain format?
我的初始數據是這個,但是我想像這樣的數據那樣寫成“ cat_id | content”格式的數據
5 Name NRIC DOB 1932.11.26 Race Chinese Sex Female ND - PATIENT CARE RECORD
4 Name NRIC DOB 1933.05.01 Race Chinese Sex Male PM - PATIENT CARE RECORD
我希望以這種格式在文本文件中寫入所需的格式:
cat_id|content
5|Name NRIC DOB 1932.11.26 Race Chinese Sex Female ND - PATIENT CARE RECORD
4|Name NRIC DOB 1933.05.01 Race Chinese Sex Male PM - PATIENT CARE RECORD
我這樣做是因為forloop中有大量內容(僅供您理解)
text_file = open("ED_Notes.txt", 'w')
for item in arr_cat:
text_file.write("%s\n" % item)
請幫忙謝謝!! :)
這應該有所幫助。
演示:
with open(filename) as infile:
toWrite = ["|".join(line.split(" ", 1)) for line in infile] #Iterate each line and split by first space and the join by |
with open(filename, "w") as outfile: #Write back to file.
for line in toWrite:
outfile.write(line)
輸出:
5|Name NRIC DOB 1932.11.26 Race Chinese Sex Female ND - PATIENT CARE RECORD
4|Name NRIC DOB 1933.05.01 Race Chinese Sex Male PM - PATIENT CARE RECORD
我認為您可以使用正則表達式執行此操作。
我會嘗試這樣的事情:
import re
text_file = open("ED_Notes.txt", 'w')
for item in arr_cat:
m = re.search("([0-9]) ([a-zA-Z].*)",item)
text_file.write(m.group(1)+"|"+m.group(2))
text_file.close()
對不起,我很着急,所以我沒有測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.