gpt4 book ai didi

python - 从普通文本中分离数字和符号

转载 作者:行者123 更新时间:2023-12-01 04:36:19 25 4
gpt4 key购买 nike

大家好,我是一名 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

你能帮我找到解决方案吗?

最佳答案

尝试这个 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']

关于python - 从普通文本中分离数字和符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31628584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com