文件A内含有地名,文件B是地名对应的坐标。
先从文件A找到地名,然后去B查到地名,提取地名之后特定格式的坐标,写入文件A。
有参考各种,侵权请联系我删除。
是小白,所以只做到了能用而已。
#!/usr/bin/python
# -*- coding: utf-8 –*-
import re
f1 = open("file1.txt", "r+", encoding='utf-8') # read and write
print("done open f1")
line1 = f1.readlines()
f1.seek(0, )
f2 = open("file2.txt", "r+", encoding='utf-8') # read only
print("done open f2\n")
line2 = f2.readlines()
# read file1 from beginning to end
for line0 in line1:
# if "name" is in this line
flag1 = re.search("name", line0)
if flag1:
# find place between " "
place = line0.split("\"")[3]
print("find place:", place)
# this is the line where place is, tab = 0,1,2,3,...
line1_copy = line1[:]
tab = line1_copy.index(line0)
# # add a comma in: line1_copy[tab+1]
# line1_copy[tab + 1] = (str(line1_copy[tab + 1]) + ',')
# print("added comma")
# find place in file2
for line in line2:
flag2 = re.search(place, line)
if flag2:
# find words between []
try:
location = re.findall(re.compile(r'[\[](.*?)[\]]', re.S), line)[0]
print("find location:", location)
except:
print("Error")
# put location in file1
if location:
# find correct line and write
new_line = (" \"coordinate\": \"[" + location + "]\"\n")
line1.insert(tab + 2, new_line)
# print(line1)
break
# write
print("start writing location")
f1.writelines(line1_copy)
print("done writing location in f1\n")
f1.close()
f2.close()
print("files closed")
写入前的文件A和B:
写入之后的效果:
后来给每行value末尾插入了逗号。
# add comma
for line0 in line1:
# if "value" is in this line
flag1 = re.search("value", line0)
if flag1:
# find value between " "
value = line0.split("\"")[3]
print("find value:", value)
# this is the line where value is(tab = 0,1,2,3,...), add a comma
line1_copy2 = line1[:]
tab = line1_copy2.index(line0)
adapt_line = (" \"value\": \"" + value + "\",\n")
line1[tab] = adapt_line
print("added comma")