指定拆分字符串的规则 Python



我正在尝试将一个句子分成三个不同的变量供以后使用,我需要指定一些规则,以我需要的方式拆分它。

例句:

sentence = 'SUPER Jumper Colour BROWN-8'

由此我需要三个变量

textBeforeColour = 'SUPER Jumper Colour'
Colour = 'BROWN'
Size = '8'

颜色(BROWN-8(将始终大写 颜色(BROWN-8(之前的任何内容都可能有一些大写的单词,但不是全部。

我已经创建了一个脚本来做到这一点,但我知道如果文本略有变化,脚本就会中断。例如

import re
text = 'SUPER Jumper Colour BROWN-8'
list = text.split()
myList = []
lastWord = list[-1]
for iterating_var in list:
if iterating_var is not list[-1]: #THIS GIVES ME THE 'BEFORE COLOUR' TEXT
myList.append(iterating_var)
if lastWord == 'SIZE':
print('ONE SIZE') #This is used when the Size is not a number but comes as ONE SIZE
else:
splitText = re.split('-',lastWord)
print(splitText[0])
print(splitText[1])
Colour = splitText[0]
size = splitText[1]

现在所有这些都有效。但是,如果字符串将使用颜色:浅蓝色 - 此脚本将保留带有句子变量的"LIGHT",而不是带有颜色变量。

import re
text = "blah Blah LIGHT BLUE-8"
if text.split()[-1] == "SIZE":
print("ONE SIZE")
else:
colour = re.findall("([A-Z ]+)-[0-9]$", text)[0][1:]
print(colour)
size = int(re.findall("[0-9]+$", text)[0])
print(size)
sentence = re.findall("(.*[^A-Z ])[A-Z ]+-[0-9]$", text)[0]
print(sentence)

对于颜色:由零个或多个大写字母和空格组成的序列,后跟连字符、零位或多个数字以及字符串的末尾

对于大小:字符串末尾的零位或多位数字

对于句子:零个或多个字符,然后是不是大写字母或空格的字符,然后是颜色的图案

您应该能够在带有捕获组的单个正则表达式中执行此操作:

import re
pat = re.compile(r'^([ws]+?)s+([A-Zs]+)-(d+)$')
sentence = 'SUPER Jumper Colour LIGHT BLUE-88'
match = pat.match(sentence)
if match:
text, color, number = match.groups()
print(text)    # SUPER Jumper Colour
print(color)   # LIGHT BLUE
print(number)  # 88

正则表达式功能强大,但可能会变得复杂。 如果您不熟悉它们,这里是re模块的文档

最新更新