【问题标题】:Python : Split a string into fragments based on a list of separatorsPython:根据分隔符列表将字符串拆分为片段
【发布时间】:2022-01-04 16:43:42
【问题描述】:

我有点努力解决以下情况...

想象一下这个字符串:

str = "three hundred + four - fifty six * eight"

有没有办法得到以下数组:

array = ["three hundred", "+", "four", "-", "fifty six", "*", "eight"]

知道我有一个包含多个运算符的列表(我猜想在字符串中用作分隔符)?

在空格分隔符上拆分字符串很容易,但我想将每个分隔部分保留为我的列表中的一项!

另外,如果不使用 re 之类的任何导入,这是否可能?

提前致谢!

【问题讨论】:

标签: python arrays split substring delimiter


【解决方案1】:

我们可以借助正则表达式拆分字符串。这里我们只需要创建一个正则表达式,你可以减少你的代码行数。

# Python3 code to demonstrate working of
# Splitting operators in String
# Using re.split()
import re

# initializing string
test_str = "three hundred + four - fifty six * eight"

# printing original string
print("The original string is : " + str(test_str))

# Using re.split()
# Splitting operators in String
res = re.split(r'(\+|\-|\*|\/)', test_str)

# printing result
print("The list after performing split functionality : " + str(res))

要了解我们如何创建正则表达式,您可以通过此链接https://www.programiz.com/python-programming/regex 获得帮助 我只为想要在 python 中的 re 模块的帮助下拆分字符串的人发布此答案。

【讨论】:

    【解决方案2】:

    不使用导入:

    mstr = "three foo fifty bar + four foo - fifty six * eight"
    dels = ['-', '*', '+', '/']
    
    # find delimeters
    split_at = [0]
    
    for item in dels:
        indices = [i for i, x in enumerate(mstr) if x == item]
        
        for index in indices:
            split_at.append(index)
    
    split_at = sorted(split_at)
    
    # split at delimeters
    split_str = []
    split_str.append(mstr[:split_at[1]])
    
    for split_id in range(2, len(split_at)):
        split_str.append(mstr[split_at[split_id-1]])
        split_str.append(mstr[split_at[split_id-1]+1:split_at[split_id]])
    
    split_str.append(mstr[split_at[-1]])
    split_str.append(mstr[split_at[-1]+1 :])
    

    结果:

    ['three foo fifty bar ', '+', ' four foo ', '-', ' fifty six ', '*', ' eight']
    

    【讨论】:

      【解决方案3】:

      这是一个函数,可以用该字符串执行您想要的操作。但是,问题更多是关于如何处理格式不正确的字符串。 Chris 在答案中的评论将您指向一个问题,该问题涉及使用抽象语法树进行标记,这是您真正需要的。本质上,这有点像从头开始编写 re 模块。无论如何:

      def deconstructor(sample, delims):
          result = []
          loader = []
          for item  in sample:
              if item not in delims:
                  loader.append(item)
              else:
                  result.append(''.join(loader).strip())
                  loader.clear()
                  result.append(item) #add that delimiter to list
          if loader: #if not required for properly formatted string
              result.append(''.join(loader).strip())
               
          return result
      
      >>> deconstructor("three hundred + four - fifty six * eight", ('+', '-', '*', '/'))
      >>> ['three hundred', '+', 'four', '-', 'fifty six', '*', 'eight']
      

      【讨论】:

        【解决方案4】:

        以更算法的方式:

        def split(string_sep, separators):
            res = []
            last = 0  # the last position of an separators
            index = 0
            for index, char in enumerate(string_sep):
                if char in operators:
                    res.append(string_sep[last:index].strip())  # strip if you dont want space enter separtors and words
                    res.append(char)
                    last = index + 1  # +1 to not take the separator
        
            # for the last add to the list
            if last <= index:
                res.append(string_sep[last:])
            return res
        

        【讨论】:

        • 哦,哇,这正是我一直在寻找并努力做到的,谢谢!
        【解决方案5】:

        假设您只需要单词,您可以使用简单的正则表达式完成此操作

        import re
        s = "three hundred + four - fifty six * eight"
        print(re.findall(r"\w+",s))
        

        结果: ['three', 'hundred', 'four', 'fifty', 'six', 'eight']

        【讨论】:

        • 这不是我真正想要的,但仍然感谢您的回答!
        • 是的,我错过了没有导入的部分。我的错。
        猜你喜欢
        • 2012-08-09
        • 2019-09-19
        • 2019-02-06
        • 2018-10-24
        • 2011-06-09
        • 2013-02-27
        • 1970-01-01
        • 2011-08-04
        • 2013-10-19
        相关资源
        最近更新 更多