【问题标题】:split numbers and symbols from normal text从普通文本中拆分数字和符号
【发布时间】:2015-10-16 04:36:26
【问题描述】:

大家好,我是一名 java 开发人员,但我是 python 的新手,我有这种平静的 java 代码,我想用 python 翻译:

    private static String split(String str) {
        List<String> output = new ArrayList<String>();
        Matcher match = Pattern.compile("[0-9,+]+|[a-z]+|[A-Z]").matcher(str);
        while (match.find()) {
            output.add(match.group());
        }
        String result="";
        for (String s:output){
            result+=s+" ";
        }
        return result;
    }

例如,如果输入为:“aaaa+1”,输出变为:“aaaa +1”。

我已经尝试过使用:

def split(nome):
    r = re.findall('\d+|.\D+', nome)
    #m = r.match(nome)
    print(r)

但不考虑符号 (+)。

这里有其他例子:

auhsuahsAsaasaA+19090 ---> auhsuahsAsaasaA +19090 
+67433998AAAAAAA ---> +67433998 AAAAAAA
ARENA-89         ---> ARENA -89

你能帮我找到解决办法吗?

【问题讨论】:

  • "aaaa+1" 输出变成:"aaaa +1" 我不清楚!
  • 我想将普通文本从符号和数字中分离出来,这里还有其他例子: auhsuahsAsaasaA+19090 ---> auhsuahsAsaasaA +19090 ; +67433998AAAAAAA ---> +67433998 AAAAAAA ;
  • 你必须在你的问题中加入新的例子(不在此处)。

标签: python split numbers symbols


【解决方案1】:

没有re模块

def divide(text):
    local_text=list(text)
    for i in range(1, len(local_text)):
        if local_text[i].isspace() or local_text[i-1].isspace():
            continue
        elif local_text[i-1].isalpha() != local_text[i].isalpha():
            local_text[i-1] += ' '
    return ''.join(local_text)

print(divide('auhsuahsAsaasaA+19090 +67433998AAAAAAA ARENA-89'))
...
auhsuahsAsaasaA +19090 +67433998 AAAAAAA ARENA -89

【讨论】:

    【解决方案2】:

    试试这个 re.findall 命令,它匹配所有连续的字母和数字(带有可选的 - 或 +)。

     re.findall(r'[A-Za-z]+|[+-]?\d+', s)
    

    示例:

    >>> import re
    >>> re.findall(r'[A-Za-z]+|[+-]?\d+', '"AAAA +2"')
    ['AAAA', '+2']
    >>> re.findall(r'[A-Za-z]+|[+-]?\d+', 'auhsuahsAsaasaA+19090')
    ['auhsuahsAsaasaA', '+19090']
    >>> re.findall(r'[A-Za-z]+|[+-]?\d+', '"AAAA +2"')
    ['AAAA', '+2']
    

    【讨论】:

    • 谢谢,但这在 "aaaaa+32" 的输出中不起作用-->['aaaaa', '+', '32']
    • 对不起,我已经快速回复:如果输入是“AAAA +2”,结果应该保持不变,但是使用您的代码,输出是“['AAAA','+','2 ']"
    • 然后使用我一开始告诉你的解决方案。已更新。
    猜你喜欢
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 2019-07-14
    • 2012-12-30
    • 1970-01-01
    • 2017-08-31
    • 2011-07-10
    相关资源
    最近更新 更多