如何将字符串的元组转换为单词?

2024-04-19 19:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

''。python中的join函数处理一个元组中的字符串。假设我们有一个字符串的“嵌套”元组,如txt输入中所示

这里有一些树的结构。这些词有词根。例如,sea seam将“se”作为一个根。它们还把“se”作为词根与“sex”和“seven”共用,但“s”只是另一个词“soup”的词根。ram没有任何共享根。你知道吗

   _ _ _ r _ _ _ a _ _ _ m%
  /
 /          _ _ _ o _ _ _ u _ _ _ p
-          /
 \        /          _ _ _a% _ _ _ m%
  \_ _ _ s          /
          \        /
           \_ _ _ e _ _ _ x%
                   \
                    \_ _ _ v _ _ _ e _ _ _ n%


#input
txt = "(ram%+s(e(a%m%+x%+ven%)+o%up%))"

#output
[ram, sea, seam, sex, seven, soup]

输出应该是一个词根用“+”分隔的单词列表。并根据以下两个条件排序

+ refers to start new word

% refers to the end of the word

希望你明白我的意思,希望你能帮忙。你知道吗


Tags: theto字符串txtwordram元组soup
1条回答
网友
1楼 · 发布于 2024-04-19 19:22:57

The way you explained the question doesn't make the most sense (to me, at least), but here's my shot at answering it:

您提供的输入格式虽然很好,但在python代码中不能直接使用。下面是一种有效的方法,可以用python表示输入中使用的符号:

# empty root node, use empty string
txt = ("", "ram", ("s", "oup", ("e", "am", "x", "ven")))

其中每个元组遵循以下形式:

(root, additions)

其中root是字符串,additions是元组或字符串。 要将txt解析为有效列表,可以编写递归函数,如下所示:

def parse(x):
    # return [x] if x is just a string.
    if isinstance(x, str): return [x]

    root, additions = x[0], x[1:] 

    words = []
    for addition in additions:

        # recursively 'flatten' all additions in current node
        sub_additions = parse(addition)

        # add the root word to each sub_addition
        sub_additions = [root + addition for addition in sub_additions]

        # add the new sub additions to the list
        words = words + sub_additions

    return words

要使用parse,只需调用它:例如parse(txt)。你知道吗

注意事项:

  • 不确定这是最简单的还是最有毒瘾的方法。你知道吗
  • 只适用于一组嵌套的元组和字符串,不接受其他类型。你知道吗
  • 不使用您在答案中使用的确切输入格式。(因为它不是有效的python?)你知道吗

相关问题 更多 >