什么是快速而肮脏的方法来将每行上用内容分隔(分隔)的文本字符串转换为 MathJax 集的字符串?

问题描述 投票:0回答:1

所需输入示例

potatoes
tomatoes
onions
carrots
bell peppers
broccoli
cucumbers
lettuce 

期望输出示例

\{
    bell peppers“, ”broccoli“, ”carrots“, ”cucumbers“, ”lettuce“, ”onions“, ”potatoes“, ”tomatoes
\}

什么是可以为我们做这件事的 python 代码?

python python-3.x latex mathjax tex
1个回答
0
投票

以下是快速的,肮脏的,并完成了工作:

import sys

combined_veggies = """
potatoes
tomatoes
onions
carrots
bell peppers
broccoli
cucumbers
lettuce 
"""

combined_fruits = """
Cherries
Pineapple
Apple
Blueberries
Grape
Strawberry
Orange
Avocacado
Watermelon
Peaches
Bananas
Raspberry
Mangoes
Plums
Blackberry

Pears

Lemon

Cantaloupe
Lime
Guava
"""


def string2setstring(istring:str, /, *, ostream=sys.stdout):
    """
        # Example of Desired Input #    

        ```lang-None 
        potatoes
        tomatoes
        onions
        carrots
        bell peppers
        broccoli
        cucumbers
        lettuce 
        ```   

        ----------------------

        # Example of Desired Output  #  

        ```lang-latex 
        \{
            “bell peppers”, “broccoli”, “carrots”, “cucumbers”, “lettuce”, “onions”, “potatoes“, “tomatoes”
        \}
        ```

    """
    seperated = istring.split("\n")
    seperated = [v.strip() for v in seperated]
    constructor = type(seperated)
    lamby = lambda ch: len(ch) > 0
    it = filter(lamby, seperated)
    seperated_veggies = constructor(it)
    seperated_veggies = list(sorted(set(seperated_veggies)))
    sep = "\u201c, \u201D"
    # the left-to-right the seperator is
    # 1. a left double-quote
    # 2. a comma
    # 3. a space character
    # 4. a right double-quote
    print(r"\{", file=ostream)
    print(4 * " ", "\u201c", sep="", end="") # no line feed at end of print-out
    print(*seperated_veggies, sep=sep, file=ostream)
    print("\u201D", sep="", end="") # no line feed at end of print-out
    print(r"\}", sep=sep, file=ostream)
    return None


istrings = [combined_veggies, combined_fruits]

for istring in istrings:
    string2setstring(istring)
© www.soinside.com 2019 - 2024. All rights reserved.