我有一个名字列表,其中有英寸大小。如:
华硕VP248QG 24''
明基XYZ123456 32“
如您所见,名字具有双英寸双引号,而名字具有正常双引号。
我有这段代码可以删除这些大小,因为我不需要它们:
def monitor_fix(s):
if ('"' in s):
return re.sub(r'\s+\d+(?:\.\d+)"\s*$', '', str(s))
if ("''" in s):
return re.sub(r"\s+\d+(?:\.\d+)''\s*$", '', str(s))
但是,它仅删除普通的双引号,而不删除双单引号。怎么处理呢?
假设大小始终用空格很好地分隔开,我们可以简单地删除包含引号的“单词”。奖励点是因为大小也可以在字符串中的任何位置。
products = ["Asus VP248QG 24'' silver", 'BenQ XYZ123456 32"']
for n, product in enumerate(products):
product_without_size = ""
for word in product.split(" "):
if not("''" in word or '"' in word): # If the current word is not a size,
product_without_size += word + " " # add it to the product name (else skip it).
products[n] = product_without_size.rstrip(" ")
print(products) # ['Asus VP248QG silver', 'BenQ XYZ123456']
使用原始帖子的格式,它看起来像这样:
def monitor_fix(product):
product_without_size = ""
for word in product.split(" "):
if not("''" in word or '"' in word): # If the current word is not a size,
product_without_size += word + " " # add it to the product name (else skip it).
return product_without_size.rstrip(" ")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句