【发布时间】:2021-06-03 19:59:17
【问题描述】:
我在 Python 中使用 Regex 在 Numeric Quantity 值之前和之后添加数量标识符。
基本上,我必须在数字数量之后添加 QtyOrd 和 Units 字样,它们不在文本中。
例如:
'PartNo-001A description 20 units some other description' => 'PartNo-001A description QtyOrd 20 units some other description'
'PartNo-001A description QtyOrd 20 some other description' => 'PartNo-001A description QtyOrd 20 units some other description'
'PartNo-001A description QtyOrd 20' => 'PartNo-001A description QtyOrd 20 units'
'PartNo-001A QtyOrd 20' => 'PartNo-001A QtyOrd 20 units'
'PartNo-001A 20 units'=> 'PartNo-001A QtyOrd 20 units'
正在使用的代码如下:
import re
def process_QtyOrd( text):
for x in re.findall("(qtyord [0-9]+ units| [0-9]+ units|qtyord [0-9]+|qtyord[0-9]+units )", text.lower()):
Text_Intermediate = "OrderQty " + str(re.search("[0-9]+", x).group()) + " Units"
Text_Final = re.sub("(qtyord [0-9]+ units|[0-9]+ units|qtyord [0-9]+|qtyord [0-9]+ units)", Text_Intermediate, text, flags= re.IGNORECASE)
return Text_Final
text1 = 'PartNo-001A description 20 units some other description'
text2 = '''
Could you please redirect the ticket to the correct sales department so they can provide assistance and a quote for the items
below.
QtyOrd 20 units some other description
'''
text3 = 'PartNo-001A description QtyOrd 20 some other description'
text4 = 'PartNo-001A description QtyOrd 20'
text5 = 'PartNo-001A QtyOrd 20'
text6 = 'PartNo-001A 20 units'
text7 = '''
Could you please redirect the ticket to the correct sales department so they can provide assistance and a quote for the items
below.
QtyOrd 20 units some other description PartNo-001A
'''
text8 = '''
Could you please redirect the ticket to the correct sales department so they can provide assistance and a quote for the items
below.
PartNo-001A
QtyOrd
20
'''
然后:
print(process_QtyOrd(text1))
print(process_QtyOrd(text2))
print(process_QtyOrd(text3))
print(process_QtyOrd(text4))
print(process_QtyOrd(text5))
print(process_QtyOrd(text6))
print(process_QtyOrd(text7))
print(process_QtyOrd(text8))
对于text8,代码不起作用。
你能帮我解决这个问题吗?
输出应该是这样的:
1. PartNo-001A description QtyOrd 20 Units some other description
2. Could you please redirect the ticket to the correct sales department so they can provide assistance and a quote for the items
below.
QtyOrd 20 Units some other description
3. PartNo-001A description QtyOrd 20 Units some other description
4. PartNo-001A description QtyOrd 20 Units
5. PartNo-001A QtyOrd 20 Units
6. PartNo-001A QtyOrd 20 Units
7. Could you please redirect the ticket to the correct sales department so they can provide assistance and a quote for the items
below.
QtyOrd 20 Units some other description PartNo-001A
8. Could you please redirect the ticket to the correct sales department so they can provide assistance and a quote for the items
below.
PartNo-001A
QtyOrd
20
units
【问题讨论】:
标签: python regex regex-lookarounds regex-group re