最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python利用正則提取字符串中數(shù)字的方法匯總

 更新時間:2026年02月15日 08:28:26   作者:detayun  
本文介紹了10種使用Python正則表達式提取股票代碼的方法,從簡單直接的findall提取所有數(shù)字,到精確匹配特定格式的代碼,再到處理多種格式的股票代碼和批量處理列表,需要的朋友可以參考下

方法1:最簡單直接的方法(推薦)

import re

text = 'cn_000858'

# 提取所有數(shù)字
numbers = re.findall(r'\d+', text)
print(numbers)  # ['000858']

# 如果只需要第一個匹配結(jié)果
if numbers:
    result = numbers[0]
    print(result)  # '000858'

方法2:使用search提取第一個數(shù)字

import re

text = 'cn_000858'

# 搜索第一個數(shù)字序列
match = re.search(r'\d+', text)
if match:
    result = match.group()
    print(result)  # '000858'

方法3:精確匹配’cn_'后的數(shù)字

import re

text = 'cn_000858'

# 匹配'cn_'后面的數(shù)字
match = re.search(r'cn_(\d+)', text)
if match:
    result = match.group(1)  # group(1)獲取第一個捕獲組
    print(result)  # '000858'

方法4:使用findall處理多個數(shù)字

import re

# 如果字符串中有多個數(shù)字
text = 'cn_000858_stock_123'

# 提取所有數(shù)字
numbers = re.findall(r'\d+', text)
print(numbers)  # ['000858', '123']

# 提取特定位置的數(shù)字
match = re.search(r'cn_(\d+)', text)
if match:
    stock_code = match.group(1)
    print(f"股票代碼: {stock_code}")  # '000858'

方法5:使用split分割提取

import re

text = 'cn_000858'

# 使用下劃線分割,取最后一部分
parts = text.split('_')
result = parts[-1]
print(result)  # '000858'

# 或者用正則split
result = re.split(r'[^\d]+', text)[-1]
print(result)  # '000858'

方法6:提取并轉(zhuǎn)換為整數(shù)

import re

text = 'cn_000858'

# 提取數(shù)字并轉(zhuǎn)換為整數(shù)(會去掉前導零)
match = re.search(r'\d+', text)
if match:
    number_str = match.group()
    number_int = int(number_str)
    print(f"字符串: {number_str}, 整數(shù): {number_int}")
    # 輸出: 字符串: 000858, 整數(shù): 858

# 如果需要保留前導零,保持字符串形式
result = match.group()
print(f"保留前導零: {result}")  # '000858'

方法7:處理多種格式的股票代碼

import re

def extract_stock_code(text):
    """
    從各種格式中提取股票代碼
    """
    # 匹配多種模式: cn_000858, sh600000, sz000001, 000858等
    patterns = [
        r'cn_(\d+)',           # cn_000858
        r'(?:sh|sz)(\d+)',     # sh600000, sz000001
        r'^(\d{6})$',          # 純數(shù)字6位
        r'_(\d{6})',           # 下劃線后6位數(shù)字
    ]
    
    for pattern in patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            return match.group(1)
    
    return None

# 測試
test_cases = [
    'cn_000858',
    'sh600000',
    'sz000001',
    '000858',
    'stock_cn_000858_data',
]

for text in test_cases:
    code = extract_stock_code(text)
    print(f"{text:20} -> [code]")

方法8:使用命名捕獲組(更清晰)

import re

text = 'cn_000858'

# 使用命名捕獲組
match = re.search(r'cn_(?P<code>\d+)', text)
if match:
    code = match.group('code')
    print(f"股票代碼: [code]")  # '000858'
    
    # 也可以用groupdict()
    print(match.groupdict())  # {'code': '000858'}

方法9:批量處理列表

import re

# 批量處理多個字符串
texts = [
    'cn_000858',
    'cn_000001',
    'sh600000',
    'sz000002',
]

# 使用列表推導式
codes = [re.search(r'\d+', text).group() for text in texts if re.search(r'\d+', text)]
print(codes)  # ['000858', '000001', '600000', '000002']

# 更安全的方式(處理可能沒有數(shù)字的情況)
codes = []
for text in texts:
    match = re.search(r'\d+', text)
    if match:
        codes.append(match.group())
print(codes)

方法10:完整的股票代碼提取工具

import re
from typing import Optional, List

class StockCodeExtractor:
    """股票代碼提取器"""
    
    @staticmethod
    def extract(text: str) -> Optional[str]:
        """
        從文本中提取股票代碼
        支持格式: cn_000858, sh600000, sz000001, 000858等
        """
        if not text:
            return None
        
        # 模式列表(按優(yōu)先級排序)
        patterns = [
            (r'cn_(\d{6})', 1),           # cn_000858
            (r'(?:sh|sz|hk)(\d{6})', 1),   # sh600000, sz000001, hk00700
            (r'^(\d{6})$', 1),             # 純6位數(shù)字
            (r'_(\d{6})', 1),              # 下劃線后6位數(shù)字
            (r'\b(\d{6})\b', 1),           # 單詞邊界的6位數(shù)字
            (r'\d+', 0),                    # 任意數(shù)字(最后備選)
        ]
        
        for pattern, group_idx in patterns:
            match = re.search(pattern, text, re.IGNORECASE)
            if match:
                code = match.group(group_idx)
                # 驗證是否為6位數(shù)字(股票代碼通常是6位)
                if len(code) == 6 and code.isdigit():
                    return code
                # 如果不是6位但也沒有其他匹配,返回它
                elif group_idx == 0:  # 最后一個模式
                    return code
        
        return None
    
    @staticmethod
    def extract_all(text: str) -> List[str]:
        """
        提取文本中所有可能的股票代碼
        """
        # 提取所有6位數(shù)字序列
        codes = re.findall(r'\b\d{6}\b', text)
        return codes
    
    @staticmethod
    def validate(code: str) -> bool:
        """
        驗證股票代碼格式
        """
        return bool(re.match(r'^\d{6}$', code))

# 使用示例
if __name__ == "__main__":
    extractor = StockCodeExtractor()
    
    test_cases = [
        'cn_000858',
        '深南電路 cn_000858',
        'sh600000',
        'sz000001',
        '000858',
        '股票代碼: 000858',
        'hk00700',
    ]
    
    print("單個提取:")
    for text in test_cases:
        code = extractor.extract(text)
        is_valid = extractor.validate(code) if code else False
        print(f"{text:25} -> {code:10} (有效: {is_valid})")
    
    print("\n批量提取:")
    text = "關注股票: cn_000858, sh600000, sz000001"
    codes = extractor.extract_all(text)
    print(f"文本: {text}")
    print(f"提取的代碼: {codes}")

方法11:處理您的Redis股票數(shù)據(jù)場景

import re
import json

def extract_stock_code_from_redis(data_str):
    """
    從Redis讀取的數(shù)據(jù)中提取股票代碼
    """
    try:
        # 先嘗試解析JSON
        data = json.loads(data_str)
        
        # 如果是字典,查找包含代碼的字段
        if isinstance(data, dict):
            # 嘗試常見的字段名
            code_fields = ['code', 'stock_code', 'symbol', 'ts_code']
            for field in code_fields:
                if field in data:
                    code = data[field]
                    # 提取數(shù)字部分
                    match = re.search(r'\d+', str(code))
                    if match:
                        return match.group()
            
            # 如果沒有找到,嘗試從所有值中提取
            for value in data.values():
                match = re.search(r'\d+', str(value))
                if match and len(match.group()) == 6:
                    return match.group()
        
        # 如果是字符串,直接提取
        elif isinstance(data, str):
            match = re.search(r'\d{6}', data)
            if match:
                return match.group()
    
    except json.JSONDecodeError:
        # 如果不是JSON,直接從字符串提取
        match = re.search(r'\d{6}', data_str)
        if match:
            return match.group()
    
    return None

# 測試
test_data = [
    '{"name": "深南電路", "code": "cn_000858"}',
    '{"ts_code": "000858.SZ", "name": "深南電路"}',
    'cn_000858',
    '000858',
]

for data in test_data:
    code = extract_stock_code_from_redis(data)
    print(f"{data:40} -> 代碼: [code]")

快速解決方案

針對您的具體需求,最簡單的代碼:

import re

# 從 'cn_000858' 提取數(shù)字
text = 'cn_000858'
result = re.search(r'\d+', text).group()
print(result)  # '000858'

# 或者一行代碼
result = re.findall(r'\d+', 'cn_000858')[0]
print(result)  # '000858'

正則表達式說明

模式說明示例
\d+匹配一個或多個數(shù)字‘000858’
\d{6}匹配恰好6個數(shù)字‘000858’
cn_(\d+)匹配’cn_'后的數(shù)字‘000858’
(?:sh|sz)(\d+)匹配sh或sz后的數(shù)字‘600000’
\b\d{6}\b單詞邊界的6位數(shù)字‘000858’

選擇最適合您場景的方法即可!

以上就是Python使用正則提取字符串中數(shù)字的方法匯總的詳細內(nèi)容,更多關于Python正則提取字符串中數(shù)字的資料請關注腳本之家其它相關文章!

相關文章

最新評論

义马市| 霍林郭勒市| 溧水县| 仁寿县| 亚东县| 黑龙江省| 永顺县| 桑植县| 仁化县| 即墨市| 星座| 永春县| 广安市| 宜州市| 文登市| 高阳县| 德清县| 新乐市| 正安县| 榆树市| 阿克陶县| 靖远县| 中山市| 临湘市| 竹北市| 泸溪县| 岑巩县| 凤山县| 绵竹市| 南郑县| 盘锦市| 波密县| 青铜峡市| 建德市| 肇庆市| 平邑县| 宁国市| 缙云县| 高唐县| 日土县| 平原县|