python-3.x 我们如何将一个由换行符分隔的文本字符串转换成一组用MathJax表示法编写的字符串?[关闭]

nnsrf1az  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(107)

已关闭,此问题需要更focused。目前不接受答复。
**想改善这个问题吗?**更新问题,使其仅通过editing this post关注一个问题。

3天前关闭。
此帖子已于2天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
Improve this question

期望输入示例

potatoes
tomatoes
onions
carrots
bell peppers
broccoli
cucumbers
lettuce

期望输出示例

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

什么是python代码可以为我们做到这一点?

gopyfrb3

gopyfrb31#

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

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)))
    left_double_quote = "\u201D"  
    right_double_quote = "\u201c" 
    sep = left_double_quote + ", " + right_double_quote
    # the left-to-right the separator is
    # 1. a right double-quote
    # 2. a comma
    # 3. a space character
    # 4. a left 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)

相关问题