【问题标题】:Separating the numbers, special characters and + or - sign from a string in python从python中的字符串中分离数字、特殊字符和+或-号
【发布时间】:2021-12-07 12:18:30
【问题描述】:

所以,我有一个类似的字符串

a = ';1'

b = '2+3'

c = '32'

d = '12-'

e = '2+;'

f = '2'

我想将它们分开得到以下结果:

a: [';', '1']

b: ['2+', '3']

c: ['3', '2']

d: ['1', '2-']

e: ['2+', ';']

`f: ['2', 无]

+ 或 - 号总是在数字之后。

【问题讨论】:

  • 2;3 呢?
  • 没有这样的例子。
  • 你在list(b)吗?
  • 我已经做到了。但我需要 2 和 + 一起,比如 b 中的 '2+' 然后 3 分开。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: python character data-cleaning


【解决方案1】:

您可以执行此类操作,这适用于您提供的所有输入。不是最 Pythonic 的方式,但它确实有效。

a = ';1'
b = '2+3'
c = '32'
d = '12-'
e = '2+;'

inputs = [a, b, c, d, e]
output = list()
for expr in inputs:
    i = 0
    string = str()
    li = list()
    while (i < len(expr)):
        if (expr[i] >= '0' and expr[i] <= '9') and i < len(expr) - 1:
            if expr[i + 1] == '+' or expr[i + 1] == '-':
                string += expr[i]
                string += expr[i + 1]
                li.append(string)
                i += 1
            else:
                li.append(expr[i])
        else:
            li.append(expr[i])
        i += 1
    output.append(li)

print(output)

【讨论】:

    【解决方案2】:

    使用内置itertools模块中的pairwise()chain()

    # itertools.pairwise is available on python 3.10+, use this function on earlier versions
    # copied from https://docs.python.org/3/library/itertools.html#itertools.pairwise
    def pairwise(iterable):
        # pairwise('ABCDEFG') --> AB BC CD DE EF FG
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)
    
    def split(s: str) -> typing.List[str]:
        # iterate pairwise: "2+3" --> [("2", "+"), ("+", "3"), ("3", None)]
        # the None is just added to get the last number right
        pairs = pairwise(chain(s, [None]))
        output = []
        for l in pairs:
            if l[1] and l[1] in "+-":
                # number is followed by a "+" or "-" --> join together
                output.append("".join(l))
            elif l[0] not in "+-":
                # number is not followed by +/-, append the number
                output.append(l[0])
        return output
    
    # checking your examples:
    strings = [';1', '2+3', '32', '12-', '2+;']
    [split(s) for s in strings]
    # [[';', '1'], ['2+', '3'], ['3', '2'], ['1', '2-'], ['2+', ';']]
    
    # bonus: everything in one line because why not
    [[("".join(l) if l[1] and l[1] in "+-" else l[0]) for l in pairwise(chain(s, [None])) if l[0] not in "+-"] for s in strings]
    # [[';', '1'], ['2+', '3'], ['3', '2'], ['1', '2-'], ['2+', ';']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2020-11-08
      相关资源
      最近更新 更多