1. 程式人生 > >隨性練習:python字典實現文本合並

隨性練習:python字典實現文本合並

open ade info isp oat bubuko ref borde round

主要用到,字典、字符串分割和連接、文件等操作

例如;有以下兩個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字典實現文本合並