Parsing strings in Python on Markup/BBCode image tags generator example

Today active content creators are publishing hundreds of articles.

Input file

e:\keif\photos\K7\K7_vref.jpg
e:\keif\photos\K7\K7_vfd_pwr.jpg
e:\keif\photos\K7\K7_trms.jpg

This file is very easy to generate using file commander, such as Total Commander, using “Copy names with UNC path” to get selected filenames and pasting result into notepad.
Now we have input data and it’s easy to process it via Python snipped below to generate link for forum page:


# xDevs.com BBCode/Textile URL generator
# Changes localfile absolute image path into repository image storage URL
# http://xdevs.com/guide/markup_gen
import sys

with open('input.txt', 'r') as f: with open('bbcode.txt','wb') as o: with open('markup.txt','wb') as b: for l in f: l = l.rstrip() # URL for image storage url = 'http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/' filename = l.strip('\r\n') # Localfile storage path to be trunicated file = filename.replace('e:\\keif\\photos\\K7\\','') # Trunicate .jpg extension filen = file.replace('.jpg','') # Debug output #sys.stdout.write('!%s' % url) #sys.stdout.write(filen) #sys.stdout.write('_s.jpg')

# Generate BBCode for forum image holders with URL o.write ('[url=%s' % url) o.write (file) o.write ('][img]%s/small/' % url) o.write (filen) o.write ('_s.jpg[/img][/url]\r\n') # Generate Textile markup image holders with URL b.write ('!%s/small/' % url) b.write (filen) b.write ('_s.jpg!:%s' % url) b.write (file) b.write ('\r\n')

Results are stored in two files:

  • markup.txt – contains Textile-format markup link to thumbnail image, which refers to big image URL
  • bbcode.txt – contains BBCode-format link or forums
!http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/small/K7_vref_s.jpg!:http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/K7_vref.jpg
!http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/small/K7_vfd_pwr_s.jpg!:http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/K7_vfd_pwr.jpg
!http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/small/K7_trms_s.jpg!:http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/K7_trms.jpg

[url=http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/K7_vref.jpg][img]http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/small/K7_vref_s.jpg[/img][/url]
[url=http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/K7_vfd_pwr.jpg][img]http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/small/K7_vfd_pwr_s.jpg[/img][/url]
[url=http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/K7_trms.jpg][img]http://dev.xdevs.com/projects/kei2001/repository/raw/photos/K7/small/K7_trms_s.jpg[/img][/url]

Author: xDevs.com Team
Created: April 7, 2015, 10:01 a.m.
Modified: July 24, 2015, 6:50 a.m.

References