![](/img/trans.png)
[英]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.