在senten中从方括号中获取子串

2024-05-01 03:25:27 发布

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

作为一个python初学者,我想问一下,我想从方括号中获取字符串,最好不要尝试从python导入任何模块。如果没有,没关系。你知道吗

例如

def find_tags
    #do some codes


x = find_tags('Hi[Pear]')
print(x)

它会回来的

1-Pear

例如,如果有多个括号

x = find_tags('[apple]and[orange]and[apple]again!')
print(x)

它会回来的

1-apple,2-orange,3-apple

如果有人能帮我,我将不胜感激谢谢!你知道吗


Tags: 模块and字符串appledeftagssomefind
3条回答

在这里,我试着解决它。这是我的密码:

bracket_string = '[apple]and[orange]and[apple]again!'

def find_tags(string1):
  start = False
  data = ''
  data_list = []
  for i in string1:
    if i == '[':
      start = True
    if i != ']' and start == True:
      if i != '[':
        data += i
    else:
      if data != '':
        data_list.append(data)
      data = ''
      start = False
  return(data_list)

x = find_tags(bracket_string)
print(x)

函数将返回位于给定字符串参数括号之间的项的列表。你知道吗

任何建议都将不胜感激。你知道吗

您可以在文本的所有字符上使用一个简单的for循环来解决这个问题。你知道吗

你必须记住,如果你是内部标签或外部标签-如果在内部将字母添加到临时列表中,如果遇到标签的结尾,则将整个模板列表作为单词添加到返回列表中。你知道吗

您可以使用单词列表的^{}来解决编号问题:

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 = ", ")

然后在每个打印命令之后指定“,”作为分隔符以获得输出。你知道吗

x看起来像:[(1, 'apple'), (2, 'orange'), (3, 'apple')]

如果您的模式是一致的,比如[sometext]sometext[sometext]...,您可以这样实现您的函数:

import re

def find_tags(expression):
   r = re.findall('(\[[a-zA-Z]+\])', expression)
   return ",".join([str(index + 1) + "-" + item.replace("[", "").replace("]", "") for index, item in enumerate(r)])

顺便说一句,您可以使用堆栈数据结构(FIFO)来解决这个问题。你知道吗

相关问题 更多 >