I'm trying to create a table in standard HTML. But i have a lot of words to be wrapped in div tags. Normally I would do this server side or something but that isn't a reality in this project. So i'm restricted to plain old web technologies. I was wondering though, if there is a python solution to my problem (i.e. creating a small script so i can run through a list of given words, output the required HTML, and then copy and paste the HTML into various html files). So if i have a list of words below, could i run a python program, and add the needed divs with the classes to each word. One problem would be the "order" needs to increment to the amount of words given.

Words

animals
cat
dog
mouse
lion

What the output should be

 <div class="Rtable Rtable--1cols">
<div style="order:0" class="Rtable-cell-head">animals</div>
    <div style="order:1;" class="Rtable-cell">cat</div>
    <div style="order:2;" class="Rtable-cell">dog</div>
    <div style="order:3;" class="Rtable-cell">mouse</div>
    <div style="order:4;" class="Rtable-cell">lion</div>
</div>

2 Answers

3
thebjorn On Best Solutions

A jinja solution:

from __future__ import print_function
from jinja2 import Template

template = Template("""
<div class="Rtable Rtable--1cols">
<div style="order:0" class="Rtable-cell-head">animals</div>
    {%- for order, animal in animals %}
        <div style="order:{{ order }};" class="Rtable-cell">{{ animal }}</div>
    {%- endfor %}
</div>
""")

animals = """
cat
dog
mouse
lion
""".split()

print(template.render(animals=list(enumerate(animals, 1))))

output:

<div class="Rtable Rtable--1cols">
<div style="order:0" class="Rtable-cell-head">animals</div>
        <div style="order:1;" class="Rtable-cell">cat</div>
        <div style="order:2;" class="Rtable-cell">dog</div>
        <div style="order:3;" class="Rtable-cell">mouse</div>
        <div style="order:4;" class="Rtable-cell">lion</div>
</div>

Pure python version:

from __future__ import print_function

template = """
<div class="Rtable Rtable--1cols">
<div style="order:0" class="Rtable-cell-head">animals</div>\
    {animals}
</div>
"""

animal_template = """
    <div style="order:{order};" class="Rtable-cell">{animal}</div>"""

animals = """
cat
dog
mouse
lion
""".split()

animal_divs = ''.join([animal_template.format(order=i, animal=animal)
                       for i, animal in enumerate(animals, 1)])
print(template.format(animals=animal_divs))

the output is the same.

update: the great convenience of Python's split is that it removes all white space (including newlines), however, if you have animal names with spaces in them (e.g. "white rhino") then you'll need to take another approach where you split by lines, strip any whitespace from each line, and skip the line if it contains only whitespace:

animals = [animal.strip() for animal in """
cat
dog
mouse
lion
""".splitlines() if animal.strip()]

(this solution is similar to the node.js solution below)

However, if your users know javascript and not Python, then a node.js solution might be better:

const animals = `
  cat
  dog
  mouse
  lion
  `.split('\n').map(v => v.trim()).filter(v => !!v);

const animal_template = (animal, order) => `<div style="order:${order+1};" class="Rtable-cell">${animal}</div>`;

const template = animals => `
<div class="Rtable Rtable--1cols">
<div style="order:0" class="Rtable-cell-head">animals</div>
    ${animals.map(animal_template).join('\n    ')}
</div>`

console.log(template(animals));
1
Mohamed Benkedadra On

you can use bs4 to create, manipulate and delete html : pip install beautifulsoup4

  • read the file containing the list of words (1 element per line)
with open('/path/to/list', 'r') as f:
    lines = f.readlines()
  • create the html you need :
from bs4 import BeautifulSoup

# creating parent
soup = BeautifulSoup('<div class="Rtable Rtable--1cols"></div>')

# adding head
new_tag = soup.new_tag('div', **{'class': 'Rtable Rtable--1cols'}) 
new_tag.string = line[0]
soup.append(new_tag)

# adding elements
for i, line in enumerate(lines[1:]):
    new_tag = soup.new_tag('div', **{'class': 'Rtable-cell', 'style': f'order:{i};'}) 
    new_tag.string = line
    soup.append(new_tag)

print(soup)