python 正则表达式 排序法
    正则表达式排序:掌握 Python 中的文本处理
    在 Python 中,正则表达式是一个强大的工具,用于匹配和处理文本。要对文本进行排序,我们可以利用正则表达式来提取和比较关键信息。
python正则表达式匹配小数    提取关键字段
    第一步是提取要排序的文本中关键字段。例如,如果我们有一个包含产品名称和价格的文本文件,我们可以使用正则表达式提取产品名称和价格信息。
    ```python
    import re
    # 假设文本文件中的内容为:
    text = "产品1 | 10.00\n产品2 | 12.50\n产品3 | 9.99"
    # 定义正则表达式模式
    pattern = r"(.) \| (\d+\.\d+)"
    # 提取匹配组
    matches = re.findall(pattern, text)
    ```
    `re.findall()` 函数将使用正则表达式模式 `pattern` 查文本中的所有匹配项。提取的匹配项存储在 `matches` 列表中,每个匹配项是一个元组,包含产品名称和价格。
    转换到字典
    为了更方便地处理提取的数据,我们可以将元组列表转换为一个字典,其中产品名称是键,价格是值。
    ```python
    products = {}
    for name, price in matches:
        products[name] = float(price)
    ```
    现在,`products` 字典包含了产品名称到价格的映射,我们可以根据价格对字典进行排序。
    按照价格排序
    要按照价格对字典进行排序,我们可以使用 `dict.items()` 方法获取键值对,然后使用 `sorted()` 函数对键值对列表进行排序。
    ```python
    sorted_products = sorted(products.items(), key=lambda x: x[1])
    ```
    `key=lambda x: x[1]` 函数指定按照字典值的第二项(价格)进行排序。`sorted_products` 是一个排好序的键值对列表。
    提取排名
    最后,我们可以从排好序的键值对列表中提取产品排名。
    ```python
    rankings = []
    for index, (name, price) in enumerate(sorted_products, start=1):
        rankings.append((index, name, price))
    ```
    `rankings` 列表包含了产品排名、名称和价格。
    完整示例
    ```python
    import re
    text = "产品1 | 10.00\n产品2 | 12.50\n产品3 | 9.99"
    pattern = r"(.) \| (\d+\.\d+)"
    matches = re.findall(pattern, text)
    products = {}
    for name, price in matches:
        products[name] = float(price)
    sorted_products = sorted(products.items(), key=lambda x: x[1])
    rankings = []
    for index, (name, price) in enumerate(sorted_products, start=1):
        rankings.append((index, name, price))