Skip to content

Instantly share code, notes, and snippets.

@GasGen
Last active December 17, 2015 22:09
Show Gist options
  • Save GasGen/5680218 to your computer and use it in GitHub Desktop.
Save GasGen/5680218 to your computer and use it in GitHub Desktop.
Localisation script for OpenWorm web.
# -*- coding: utf-8 -*-
#OpenWorm Translate the website! - Localisation script
#author: Gaston Gentile
from bs4 import BeautifulSoup
import os
os.system('clear')
print 'OpenWorm site translator'
print 'Let\'s go, translate the site!\n'
option = input('what do you want do? \n1-Create source file\n2-Translate the Site\noption: ')
if option == 1:
html = open('OpenWorm.html', 'rw')#Open the original html of the website.
soup = BeautifulSoup(html)#convert html in to soup
language_name = raw_input('\nFirst write the language name of the new translation: ')#For example "Spanish"
extention = language_name[:2]
#Create a folder with the name of language and a file with the language extention.
if not os.path.isdir(language_name):
os.mkdir(language_name)
resource_file = open("%s/openWorm.%s" %(language_name, extention), 'w+')
print ('The folder %s has been created.'%language_name)
else:
print ('The directory %s already exists'%language_name)
exit()
#I use these tags, because between them have strings.
tags_id = soup.find_all(('a','p', 'h1', 'h2'), id=True)
for n in tags_id:
tag = ("%s = \n" % n['id'])
resource_file.writelines(tag)
print tag
print ('The resource file openworm.%s has been created.'%extention)
html.close()
resource_file.close()
if option == 2:
#select the language of the translation
language_translation = raw_input('Generate translation of: ')
#Open the html to translate
html = open('%s/OpenWorm.html'%language_translation, 'r+')
#convert html in to soup
soup = BeautifulSoup(html)
#Open the resource file (with the translated words)
resource = open('%s/openWorm.%s'%(language_translation, language_translation[:2]))
values = {}
#Dictionary generate with the for loop and the resource file
for line in resource:
(key, val) = line.split(':')
values[str(key)] = val.replace('\n', '')
resource.close()
tag = soup.find_all('p')
for tag_content in tag:
tag_content.clear()
for key, value in values.iteritems():
content = soup.find(id=key)
if content is not None: #This line fix the error: "NoneType Object"
if content.name == 'p':
content.append(value)
else:
content.contents[0].replace_with(value)
html_translated.write(str(soup))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment