How To Search And Replace Text From One File To Another Using Python?
I have a file file1.txt : I Show more flower you can see by link All is Beautyfull.You Can View Here ! Link View : http://lincoln.com/view/12432134/flower1.jpg http://lincoln.
Solution 1:
Try this
import urlparse
import os
def file_merge(file1name,file2name):
file1contents = list()
file2contents = list()
file1 = open(file1name, 'U')
file1contents = file1.readlines()
file1.close()
file2 = open(file2name, 'U')
file2contents = file2.readlines()
file2.close()
file3contents = []
for link in file2contents:
temp = urlparse.urlsplit(link)
dirname, filename = os.path.split(temp.path)
file3contents.append(link)
linkin1 = False
for l_link in file1contents[4:]:
if l_link.endswith(filename):
linkin1 = True
if not linkin1:
urllist = list(temp)
urllist[1] = 'kashi.com'
file3contents[-1] = urlparse.urlunsplit(urllist)
file3 = open(file1name,'w')
for line in file3contents:
file3.write(line)
file3.close()
file_merge('/tmp/file1.txt','/tmp/file2.txt')
Solution 2:
try this, please:
with open('file2.txt','r') as f2:
dic2 = {}
li2 = []
for line in f2:
spli = line.rstrip().replace('http://','').split('/')
dic2[(spli[0],spli[-1])] = line if line[-1]=='\n' else line+'\n'
li2.append((spli[0],spli[-1]))
with open('file1.txt','r') as f1,open('file3.txt','w') as f3:
itr1 = iter(f1)
for line in itr1:
f3.write(line)
if line.strip()=='':
break
for line in itr1:
if line.strip():
spli = line.rstrip().replace('http://','').split('/')
x = (spli[0],spli[-1])
if x in li2:
f3.write(dic2[x])
li2.remove((spli[0],spli[-1]))
klu = '\n' if line.rstrip()==line else ''
# to add a blank line if the last line wasn't '\n'-ended
f3.write(klu + '\nMore Link VIew:\n\n')
for remain in li2:
f3.write(dic2[remain])
f3.write('++++++++++++++++++++++++++++++++++++++++ ')
Solution 3:
This works; however it really seems to me very strange question in the first place...sorry...
from urlparse import urlparse
import os.path
def read_links2(f):
for line in f:
line = line.strip()
url = urlparse(line)
if url.scheme in ('http', 'https'):
key = (url.netloc, os.path.split(url.path)[1])
yield (key, url)
links2 = dict(read_links2(open('f2.txt', 'U')))
for line in open('f1.txt', 'U'):
line = line.rstrip()
url = urlparse(line)
if url.scheme in ('http', 'https'):
key = (url.netloc, os.path.split(url.path)[1])
if key in links2:
print links2[key].geturl()
else:
print line
print 'More Link VIew:'
for url in links2.values():
if url.netloc == 'kashi.com':
print url.geturl()
print '+++++++++++++++++++'
Post a Comment for "How To Search And Replace Text From One File To Another Using Python?"