Skip to content

Instantly share code, notes, and snippets.

@bukowa
Last active December 19, 2019 00:13
Show Gist options
  • Save bukowa/8f72ae14b895736e53db519a3cb396ae to your computer and use it in GitHub Desktop.
Save bukowa/8f72ae14b895736e53db519a3cb396ae to your computer and use it in GitHub Desktop.
css get classes for values
from typing import List
import tinycss2
import tinycss2.ast
def get_desired(filename):
"""
Read desired css line by line from a file.
"""
with open(filename, 'r') as f:
return [x.strip() for x in f.readlines() if x != '']
def get_file(filename):
with open(filename, 'rb') as f:
return f.read()
def get_stylesheet(filename):
f = get_file(filename)
s = tinycss2.parse_stylesheet_bytes(
f,
protocol_encoding='utf-8'
)[0]
return s
def parse_classes(prelude: List) -> List:
"""
Example:
>> classes = parse_classes(prelude)
>> print(classes)
>> ['.', 'divi-podcast-subscribe-powerpress', ' ', '.', 'pp-sub-widget', ',']
"""
text = []
for klass in prelude:
text.append(klass.serialize())
text.reverse()
if text[0] == ' ':
text.pop(0)
if text[0] != ',':
text.insert(0, ',')
text.reverse()
return text
def parse_stylesheet(stylesheet, desired_classes: List):
desired_dict = {}
for rule in stylesheet:
for klass in desired_classes:
desired_dict[klass] = desired_dict.get(klass, [])
# this is important
rule_text = rule.serialize().split('\n')
rule_text = [x.strip() for x in rule_text]
if klass.strip() in rule_text:
class_text = parse_classes(rule.prelude)
desired_dict[klass].append(class_text)
return desired_dict
def main():
stylesheet = get_stylesheet('./scss/app.css')
desired_classes = get_desired('./desired.txt')
print('Parsing for classes: ', desired_classes)
d = parse_stylesheet(
stylesheet=stylesheet,
desired_classes=desired_classes,
)
with open('./output.txt', 'w') as f:
for desired in d.keys():
if d[desired]:
d[desired][-1].pop(-1)
text = ''.join([''.join(x) for x in d[desired]]).replace('\n', '')
f.write(f'{desired}\n=======================\n{text}\n=======================\n\n\n')
print('Success..')
for k, v in d.items():
print('"{0}", Len: {1}'.format(k, len(v)))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment