随性练习:python字典实现文本合并
Posted 阳光宝贝-沐沐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了随性练习:python字典实现文本合并相关的知识,希望对你有一定的参考价值。
主要用到,字典、字符串分割和连接、文件等操作
例如;有以下两个txt文本,要合并成一个
代码:
address_book1 = {}
address_book2 = {}
def read_address():
\'\'\'
read content from txt
:return
\'\'\'
with open("address1.txt","r") as f1:
lines1 = f1.readlines() #返回列表
for line in lines1:
line = line.strip() #去空白
content = line.split(",") #切割
address_book1[content[0]] = content[1]
with open("address2.txt","r") as f2:
lines2 = f2.readlines() #返回列表
for line in lines2:
line = line.strip() #去空白
content = line.split(",") #切割
address_book2[content[0]] = content[1]
def merge_address(): #合并
lines = []
header = "姓名\\t 电话\\t 邮箱\\n"
lines.append(header)
for key in address_book1:
line = ""
if key in address_book2:
line += "\\t".join([key,address_book1[key],address_book2[key]]) #拼接
line += "\\n"
else:
line += "\\t".join([key,address_book1[key],"********"]) #拼接
line += "\\n"
lines.append(line)
for key2 in address_book2:
line = ""
if key2 not in address_book1:
line += "\\t".join([key2,"************",address_book2[key2]]) #拼接
line += "\\n"
lines.append(line)
with open("new_address_book.txt","w",encoding="utf-8") as f3:
f3.writelines(lines)
# for i in lines: #逐行写
# f3.write(i)
if __name__ == "__main__":
read_address()
# print(address_book1)
# print(address_book2)
merge_address()
效果:
以上是关于随性练习:python字典实现文本合并的主要内容,如果未能解决你的问题,请参考以下文章