Created
September 20, 2017 16:12
-
-
Save oal/c4f17fd8f2df398e84a23c73daf9c142 to your computer and use it in GitHub Desktop.
Quick script for extracting language strings from Laravel projects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import os | |
import json | |
from collections import OrderedDict | |
def extract_with(directory, before, after): | |
translations = {} | |
for root, dirs, files in os.walk(directory): | |
for file in files: | |
with open(root + '/' + file, 'r') as f: | |
data = f.read() | |
strings = data.split(before)[1:] | |
for string in strings: | |
parts = string.split(after) | |
key = parts[0] | |
if string not in translations and key[0] in ["'", '"'] and key[0] == key[-1]: | |
translations[key[1:-1]] = '' | |
return translations | |
def extract(directory): | |
return { | |
**extract_with(directory, '__(', ')'), | |
**extract_with(directory, '@lang(', ')'), | |
**extract_with(directory, 'trans(', ')') | |
} | |
translations = { | |
**extract('resources/views'), | |
**extract('app') | |
} | |
try: | |
with open('resources/lang/nb.json', 'r') as f: | |
existing = json.load(f) | |
except FileNotFoundError: | |
existing = {} | |
combined = { | |
**translations, | |
**existing | |
} | |
combined = OrderedDict(sorted(combined.items())) | |
with open('resources/lang/nb.json', 'w') as f: | |
f.write(json.dumps(combined, ensure_ascii=False, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment