Python字符串仅在sp前面或后面的数字上拆分

2024-09-29 23:31:56 发布

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

我有下面的字符串,我想分成一个列表。我想知道如何在前面和后面有空格的数字上拆分它。你知道吗

我试过以下方法,几乎就是我所需要的。你知道吗

\s+(?=\d)|(?<=\d)\s+

尝试

import re

# Find the numeric values: 
tmplist = re.split(r'\s+(?=\d)|(?<=\d)\s+', 'Dual 425mm AutoCannon 25') 


# Print the list
print(tmplist)

结果如下:

['Dual', '425mm AutoCannon', '25']

这是期望的结果:

['Dual 425mm AutoCannon', '25']

Tags: the方法字符串importre列表数字find
2条回答

一种方法是匹配一个空格,并使用正向前瞻来断言右边的数字是1+个数字,之后是非空格字符:

\s(?=\d+(?!\S))
  • \s空白字符
  • (?=正面展望,断言右边的内容
    • \d+匹配1+个数字
    • (?!负面展望,断言右边的不是
      • \S匹配非空白字符
    • )关闭负面展望
  • 关闭正面展望

Regex demo| Python demo

您的代码可能如下所示:

import re
tmplist = re.split(r'\s(?=\d+(?!\S))', 'Dual 425mm AutoCannon 25') 
print(tmplist)

结果

['Dual 425mm AutoCannon', '25']

参见regulex视觉

enter image description here

不完全是最漂亮的,但由于正则表达式有时很难阅读,或者返回并记住为什么要这样做,这里有一个函数可以完成您正在尝试做的事情。我把你的文字扩展了一点,只是为了确保它能继续工作。你知道吗

def split_on_number(text):

    final = [text.split()[0]]  # Autoload the first item
    for i in text.split()[1:]: # Ignore the first item

        try:
            #Try to convert it to a float
            float(i)           

        except ValueError: 
            # if there's an issue, append to last item
            final[-1] = " ".join([final[-1], i]) 

        else:
            # if you can covnert to a float, then append it
            final.append(i)    

    return final

print(split_on_number('Dual 425mm AutoCannon 25 with another 4 items'))
# ['Dual 425mm AutoCannon', '25 with another', '4 items']

相关问题 更多 >

    热门问题