python中的价格解析如何在第一个数字出现之前将列表中的所有字符串拆分一次?

2024-06-17 15:28:56 发布

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

我有一个字符串列表,如下所示:

输入:

prices_list = ["CNY1234", "$ 4.421,00", "PHP1,000", "€432"]

我想删除除isdigit()'.|,'之外的所有内容。换句话说,我想在第一次出现任何带有maxsplit=1的数字之前拆分:

所需输出:

["1234", "4.421,00", "1,000", "432"]

第一次尝试(两个regex替换)

# Step 1: Remove special characters
prices_list = [re.sub(r'[^\x00-\x7F]+',' ', price).encode("utf-8") for price in prices_list]
# Step 2: Remove [A-Aa-z]
prices_list = [re.sub(r'[A-Za-z]','', price).strip() for price in prices_list]

电流输出:

['1234', '$ 4.421,00', '1,000', '432']   # $ still in there

第二次尝试(仍然有两个regex替换):

prices_list = [''.join(re.split("[A-Za-z]", re.sub(r'[^\x00-\x7F]+','', price).encode("utf-8").strip())) for price in price_list]

这(当然)会产生与我第一次尝试相同的结果。而且,这不是很短,看起来很难看。有没有更好(更短)的方法?你知道吗

第三次尝试(列表理解/嵌套for-循环/无正则表达式):

prices_list = [''.join(token) for token in price for price in price_list if token.isdigit() or token == ',|;']

产生:

NameError: name 'price' is not defined

如何最好地解析上述价目表?你知道吗


Tags: inretoken列表forsteppriceremove
2条回答

如果只需要留下特定的字符,最好告诉regex执行以下操作:

import re

prices_list = ["CNY1234", "$ 4.421,00", "PHP1,000", "€432"]

prices = list()
for it in prices_list:
    pattern = r"[\d.|,]+"
    s = re.search(pattern, it)
    if s:
        prices.append(s.group())

> ['1234', '4.421,00', '1,000', '432']

问题

如果我错了,请纠正我,但实际上你是在试图删除符号之类的东西,只留下任何尾随数字,对吗?你知道吗

I would like to split before the first occurrence of any digit

我觉得,这是构建您正试图解决的regex问题的最简单方法。你知道吗

你知道吗

解决方案

# -*- coding: utf-8 -*-
import re

# Match any contiguous non-digit characters
regex = re.compile(r"\D+")

# Input list
prices_list = ["CNY1234", "$ 4.421,00", "PHP1,000", "€432"]

# Regex mapping
desired_output = map(lambda price: regex.split(price, 1)[-1], prices_list)

这给了我['1234', '4.421,00', '1,000', '432']作为输出。你知道吗

你知道吗

解释

之所以这样做是因为lambda和map函数。基本上,map函数接受lambda(一个可移植的单行函数,如果您愿意的话),并对列表中的每个元素执行它。负索引采用split方法生成的匹配列表的最后一个元素

基本上,这是因为假设您不希望输出中有任何初始非数字。你知道吗

你知道吗

注意事项

  • 此代码不仅在结果子字符串中保留.,,而且在结果子字符串中保留所有字符。因此,"$10e7"的输入字符串将输出为'10e7'

  • 如果只使用数字和.,,例如"10.00"作为输入字符串,则会在输出列表的相应位置获得'00'

如果这些都不是您想要的行为,那么您就必须去掉regex.split(price, 1)旁边的负索引,并对得到的列表列表进行进一步处理,这样您就可以处理使用regex时出现的所有讨厌的边缘情况。你知道吗

不管是哪种方式,我都会尝试用更极端的例子来证明这是你需要的。你知道吗

相关问题 更多 >