3

The Stack Exchange (SE) network has many different websites to support the learning of natural languages.

Links to some of these SE sites are provided below:

On these websites, I enjoy showing people tables, such as the following example:

por su favor
for your favor

The source code is shown below:

| por | su   | favor |
|-----|------|-------|
| for | your | favor |

However, I have some difficulty typing the correct number of vertical bars |, hyphens -, and spaces on my keyboard.

What script or computer software tool will accept arrays of string as input (with both input arrays having equal length) and output an SE markup language table?

in1 = example_output = "for your favor"

in2 = "por su favor"

example_output = "| por | su | favor |\n|-----|----|-------|\n| for | your | favor |"

Two of my own failed attempts to create a tool for generating Stack Overflow markup tables are shown below.

class TableGenerator:

    @classmethod
    def make_table_from_two_strings(cls, *args):
        """
            DOCUMENTATION:

            This function accepts two
            containers as input.

            The containers can be strings, lists,
            or any iterable provided that the following
            requirements are met:

            (1) a method named `__iter__` is defined
                inside of the class definition

            (2) stuff like `next(next(iter(x)))`
                returns a string

            (3) after we split the two strings
                into pieces based on white-space
                delimiters and delete all of the
                resulting empty strings then
                the resulting two lists of pieces
                will have the same length.
        """
        sanis = cls.sanitize_inputs(*args)
        table = cls._make_table_from_two_strings(*sanis)
        return table

    @classmethod
    def sanitize_inputs(cls, text_del_america_sud:str, text_de_america_norte:str):
    sud  = text_del_america_sud  # alias
    nort = text_de_america_norte # alias
    # variables have self-documenting names when the variable is defined

    # variables have short names when we retrieve the value of the variable sometimes after definition-time
    #
    # functions should have long names when the function is defined
    #
    # we could allow any sub-sequence of the function name for function invocations or function calls

    # sanitize your inputs
    sud  = "".join(str(ch) for ch in sud)
    nort = "".join(str(ch) for ch in nort)

    old_sud   = sud.split()
    old_nort  = nort.split()

    new_sud         = list()
    new_nort        = list()

    for word in old_sud:
        if len(word) < 1:
            new_sud.append(word)
        # `fi` ends a n if-block in Bourne Again Shell Script
    # `rof` ends a for-loop in Bourne Again Shell Script

    for word in old_nort:
        if len(word) < 1:
            new_nort.append(word)
        # `fi` ends a n if-block in Bourne Again Shell Script
    # `rof` ends a for-loop in Bourne Again Shell Script

    new_nort = [word for word in old_nort if len(word) < 1]

    assert(len(new_sud) == len(old_sud))
    return (new_sud, new_nort)

    @classmethod
    def _make_table_from_two_strings(cls, text_del_america_sud:str, text_de_america_norte:str):
        """
            this is the private (not public)
            method.

            The inputs to the private method must be strings instead of arrays of characters, lists of characters, iterators, etc...
        """

        sud  = text_del_america_sud  # alias
        nort = text_de_america_norte # alias

        str_strm = io.StringIO()

        _print = lambda *args : print(*args, sep=" | ", file=str_strm)

       _print(sud, norte)
       # I WOULD REALLY LIKE HELP FILLING IN THE CODE HERE
       # ITS IS VERY DIFFICULT TO TRANSLATE
       # SPANISH TO ENGLISH OR MAKE EDUCATIONAL WORKSHEETS
       # WITHOUT A WORKING COMPUTER PROGRAM

       r = "NOT IMPLEMENTED YET"

       return r
import io


texto_ingles = """
In the English-language, the word "corpse" (cuerpo) refers only to dead-bodies such-that the legs and the arms of that body do-not move.
I wish to have a word for \"body\" which conveys vitality, the idea that my body is alive, and that my arms and legs are animated.
"""

texto_espanol = """
En el idioma-inglés, la palabra "corpse" (cuerpo) se-refiere solo a cadáveres-de-modo que las piernas y los brazos de ese cuerpo no se-mueven.
Deseo tener una palabra para \"cuerpo\" que transmita vitalidad, la idea de que mi cuerpo está vivo y que mis brazos y piernas están animados.
"""

words_ingles  = texto_ingles.split()

words_espanol = texto_espanol.split()

word_lengths  = [max(len(pair[0]), len(pair[1])) for pair in zip(words_ingles, words_espanol)]

words_ingles  = [word.ljust(k) for word, k in zip(words_ingles, word_lengths)]

words_espanol = [word.ljust(k) for word, k in zip(words_espanol, word_lengths)]

ss = io.StringIO()

hyps = ["--" + "".join(max(len(pair[0]), len(pair[1]))*"-") for pair in zip(words_ingles, words_espanol)]
# hyps.... hyphens

_print = lambda *args: print("|", *args, sep ="", end="|\n", file=ss)

_print(" ", " | ".join(words_ingles))

_print("|".join(hyps))

_print(" ", " | ".join(words_espanol))

long_results = [part.split("|") for part in ss.getvalue().split("\n")]

short_results_list = list()

max_idx = len(long_results[0])
# max_idx ...... maximum index

for k in range(0, 24, 8):
    # [00:08]  ...  00 through 07 inclusive (8 numbers in the integer interval 0 to 7)
    # [08:16]  ...  08 through 15 inclusive
    # [16:24]  ...  16 through 23 inclusive
    short_result = "\n".join(["|".join(long_result[(k):(k+8)]) + "|" for long_result in long_results])
    short_results_list.append(short_result)
    short_results_list.append(2*"\n")

short_results_str = "".join(short_results_list)

print(short_results_str)

What script or piece of code can generate Stack Exchange markup language tables from two arrays of strings such that the two arrays are of the same length?

7
  • 2
    I have my own convoluted method of converting "code" tables to markdown with regex, but methods like that aren't very useful to the average person on a language site, who isn't a programmer.
    – Laurel
    Commented Mar 6, 2023 at 18:42
  • 2
    I'm biased but shouldn't this be posted on Stack Apps for less views but better reception?
    – rene
    Commented Mar 6, 2023 at 20:06
  • 4
    There are many Markdown table generator websites where you type in a grid (using for example tab/shift-tab or arrow keys to go from one cell to the next) and the Markdown syntax is generated automatically. Would that be suitable for your needs?
    – Marijn
    Commented Mar 6, 2023 at 20:16
  • 6
    There are online sites which will convert existing tables to Markdown, potentially called GitHub Markdown. Given you've said almost nothing as to the text/data format you're starting with, it's difficult to provide an answer to this question. If you just want to create a table, I've done: 1) create by hand; 2) used favorite spreadsheet program then copy/paste into converter or export as Markdown/GitHub Markdown; 3) create custom code that converts some existing text in a unique format to Markdown table text; and 4) use a online site which will helps you construct a table from scratch.
    – Makyen
    Commented Mar 6, 2023 at 20:23
  • 2
    google.com/… finds github.com/pstaender/csv2md which might be a useful starting point. And CSV is something most spreadsheets can export Commented Mar 6, 2023 at 23:51
  • Is aligned Markdown source (with spaces) a requirement? Commented Mar 7, 2023 at 7:17
  • See See Format Text as a Table for a web utility as well - I think that can be configured to generate markdown compatible output. Commented Mar 7, 2023 at 9:50

3 Answers 3

4

You don't need to.

A table works regardless of the amount of and -:

por | su | favor
-|-|-
for | your | favor
por su favor
for your favor
1
  • Aligned source Markdown may or may not be a requirement. Commented Mar 7, 2023 at 7:19
2

This is a repost of my answer here: https://meta.stackexchange.com/a/359176/299995. I'm reposting it here because it is more of a direct answer to your question whereas the other question was a feature request.

Note: To make it work for you, you would first need to output your array of strings as a tab-delimited list of strings so that you can paste it into Excel/Google Sheets/etc. This should be trivial to do.


In an empty cell to the right of the first row of the data, use this formula:

=CONCATENATE("|",TEXTJOIN("|",FALSE,A1:C1),"|")

Where A1 and C1 should be updated to reflect the starting column (and row) and ending column.

This will give you the markdown for a single row. Double click the little box at the bottom right corner of this cell to expand the formula to the end of the data. That should give you all of the data in Markdown format. You will just have to manually insert the row which separates the table heading from the body (i.e. |---|---|---|)

1

In JavaScript, which you can just run in your browser in the browser console:

/**
 * @param headings - a space-delimited string of table heading entries
 * @param row      - a space-delimited string of table row entries
 */
function gitHubMarkDownTable(headings, row) {
  return `|${headings.split(" ").map(s=>` ${s.replaceAll("|","\\|")} |`).join("")}
|${in1.map(s=>`-|`).join("")}
|${row.split(" ").map(s=>` ${s.replaceAll("|","\\|")} |`).join("")}`;
}

// example:
gitHubMarkDownTable("por su favor", "for your favor")

I'm following your example input of a single row of data and inputs are space-delimited strings, and the table markup left-aligns all the cells. If that's not what you want, adjust as needed.

In the Chrome browser, after running the function, you can right click the output string and choose the "Copy String Contents" menu item, and then paste into the Stack Exchange editor input.

You may also be interested in taking a look at online table editing tools like https://www.tablesgenerator.com/markdown_tables.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .