<p>您可以在文本的所有字符上使用一个简单的for循环来解决这个问题。你知道吗</p>
<p>你必须记住,如果你是<em>内部</em>标签或<em>外部</em>标签-如果在内部将字母添加到临时列表中,如果遇到标签的结尾,则将整个模板列表作为单词添加到返回列表中。你知道吗</p>
<p>您可以使用单词列表的<a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow noreferrer">^{<cd1>}</a>来解决编号问题:</p>
<pre><code>def find_tags(text):
inside_tag = False
tags = [] # list of all tag-words
t = [] # list to collect all letters of a single tag
for c in text:
if not inside_tag:
inside_tag = c == "[" # we are inside as soon as we encounter [
elif c != "]":
t.append(c) # happens only if inside a tag and not tag ending
else:
tags.append(''.join(t)) # construct tag from t and set inside back to false
inside_tag = False
t = [] # clear temporary list
if t:
tags.append(''.join(t)) # in case we have leftover tag characters ( "[tag" )
return list(enumerate(tags,start=1)) # create enumerated list
x = find_tags('[apple]and[orange]and[apple]again!')
# x is a list of tuples (number, tag):
for nr, tag in x:
print("{}-{}".format(nr, tag), end = ", ")
</code></pre>
<p>然后在每个打印命令之后指定“,”作为分隔符以获得输出。你知道吗</p>
<p><code>x</code>看起来像:<code>[(1, 'apple'), (2, 'orange'), (3, 'apple')]</code></p>