Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过匹配字符从字符串中获取子字符串_Python - Fatal编程技术网

Python 通过匹配字符从字符串中获取子字符串

Python 通过匹配字符从字符串中获取子字符串,python,Python,我试图从我拥有的字符串列表中提取价格 以下是价格表示例: 从价格表中,我想提取每月价格和每日价格 如果MonthlyPrice不存在,则为NA 我尝试了以下代码: for item in PriceList: if item.find("Monthly")!= -1: MonthlyPrice = (item[8:]) if item.find("Yearly")!= -1: YearlyPrice = (item[7:]) if item

我试图从我拥有的字符串列表中提取价格

以下是价格表示例:

从价格表中,我想提取每月价格和每日价格

如果MonthlyPrice不存在,则为NA

我尝试了以下代码:

for item in PriceList:
    if item.find("Monthly")!= -1:
        MonthlyPrice = (item[8:])
    if item.find("Yearly")!= -1:
        YearlyPrice = (item[7:])
    if item.find("Weekly")!= -1:
        WeeklyPrice = (item[7:])
但它不起作用,请帮我解决这个问题

预期结果

列表中第一个示例的printWeeklyPrice将为您提供3600.00美元
列表中第一个示例的printDailyPrice将为您提供-NA。

与其笨拙地解析列表中的孤立字符串,不如构建一个字典

>>> prices = ['Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00']
>>> prices = dict(time_price.split(':') for time_price in prices[0].split())
>>> prices
{'Monthly': '$33,600.00', 'Daily': '$3,000.00', 'Weekly': '$8,400.00'}
从这里你可以随心所欲地提取你想要的东西

>>> prices['Daily']
'$3,000.00'
>>> prices.get('NotFound', 'NA')
'NA'
请注意,如果您计划在将来对价格进行任何运算,将其转换为浮动值是一个好主意

>>> prices = {k:float(v[1:].replace(',', '')) for k,v in prices.items()}
>>> prices
{'Monthly': 33600.0, 'Daily': 3000.0, 'Weekly': 8400.0}

与其笨拙地解析列表中的孤立字符串,不如构建一个字典

>>> prices = ['Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00']
>>> prices = dict(time_price.split(':') for time_price in prices[0].split())
>>> prices
{'Monthly': '$33,600.00', 'Daily': '$3,000.00', 'Weekly': '$8,400.00'}
从这里你可以随心所欲地提取你想要的东西

>>> prices['Daily']
'$3,000.00'
>>> prices.get('NotFound', 'NA')
'NA'
请注意,如果您计划在将来对价格进行任何运算,将其转换为浮动值是一个好主意

>>> prices = {k:float(v[1:].replace(',', '')) for k,v in prices.items()}
>>> prices
{'Monthly': 33600.0, 'Daily': 3000.0, 'Weekly': 8400.0}
试试这个:

for item in PriceList:
    for line in item.splitlines():
        if line.startswith('Daily:'):
            DailyPrice = line[len('Daily:'):]
        if line.startswith('Weekly:'):
            WeeklyPrice = line[len('Weekly:'):]
        if line.startswith('Monthly:'):
            MonthlyPrice = line[len('Monthly:'):]
试试这个:

for item in PriceList:
    for line in item.splitlines():
        if line.startswith('Daily:'):
            DailyPrice = line[len('Daily:'):]
        if line.startswith('Weekly:'):
            WeeklyPrice = line[len('Weekly:'):]
        if line.startswith('Monthly:'):
            MonthlyPrice = line[len('Monthly:'):]
具有函数和特定正则表达式模式的完整解决方案:

import re

price_list = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
              'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
              'Daily:$1,800.00\n\nWeekend:$2200.00',
              'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

base_dict = {'Yearly': 'NA', 'Monthly': 'NA', 'Weekly': 'NA', 'Daily': 'NA'}
pat = re.compile('(?:(Yearly|Monthly|Weekly|Daily):(\$[\d.,]+))')

for p_str in price_list:
    result_d = dict(base_dict)
    result_d.update(pat.findall(p_str))
    print('Yearly: {Yearly}, Monthly: {Monthly}, Weekly: {Weekly}, Daily: {Daily}'.format(**result_d))
输出:

Yearly: NA, Monthly: $15,120.00, Weekly: $3,600.00, Daily: NA
Yearly: NA, Monthly: $33,600.00, Weekly: $8,400.00, Daily: $3,000.00
Yearly: NA, Monthly: NA, Weekly: NA, Daily: $1,800.00
Yearly: NA, Monthly: $24,000.00, Weekly: $6,000.00, Daily: NA
具有函数和特定正则表达式模式的完整解决方案:

import re

price_list = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
              'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
              'Daily:$1,800.00\n\nWeekend:$2200.00',
              'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

base_dict = {'Yearly': 'NA', 'Monthly': 'NA', 'Weekly': 'NA', 'Daily': 'NA'}
pat = re.compile('(?:(Yearly|Monthly|Weekly|Daily):(\$[\d.,]+))')

for p_str in price_list:
    result_d = dict(base_dict)
    result_d.update(pat.findall(p_str))
    print('Yearly: {Yearly}, Monthly: {Monthly}, Weekly: {Weekly}, Daily: {Daily}'.format(**result_d))
输出:

Yearly: NA, Monthly: $15,120.00, Weekly: $3,600.00, Daily: NA
Yearly: NA, Monthly: $33,600.00, Weekly: $8,400.00, Daily: $3,000.00
Yearly: NA, Monthly: NA, Weekly: NA, Daily: $1,800.00
Yearly: NA, Monthly: $24,000.00, Weekly: $6,000.00, Daily: NA

您可以这样做,首先从PriceList中的每个数据字符串创建一个临时prices字典,然后使用dictionary方法确定字符串中是否有特定的值。在字典中查找东西非常快,因此这种实现方法也相当有效

PriceList = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
             'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
             'Daily:$1,800.00\n\nWeekend:$2200.00',
             'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

for data in PriceList:
    prices = dict(item.split(':') for item in data.split('\n\n'))
    MonthlyPrice = prices.get("Monthly", "NA")
    YearlyPrice = prices.get("Yearly", "NA")
    WeeklyPrice = prices.get("Weekly", "NA")
    print('MonthlyPrice: {:<10}, YearlyPrice: {:<10}, WeeklyPrice: {:<10}'.format(
            MonthlyPrice, YearlyPrice, WeeklyPrice))

您可以这样做,首先从PriceList中的每个数据字符串创建一个临时prices字典,然后使用dictionary方法确定字符串中是否有特定的值。在字典中查找东西非常快,因此这种实现方法也相当有效

PriceList = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
             'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
             'Daily:$1,800.00\n\nWeekend:$2200.00',
             'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

for data in PriceList:
    prices = dict(item.split(':') for item in data.split('\n\n'))
    MonthlyPrice = prices.get("Monthly", "NA")
    YearlyPrice = prices.get("Yearly", "NA")
    WeeklyPrice = prices.get("Weekly", "NA")
    print('MonthlyPrice: {:<10}, YearlyPrice: {:<10}, WeeklyPrice: {:<10}'.format(
            MonthlyPrice, YearlyPrice, WeeklyPrice))

上一个列表中的孤独的\n\n周是怎么回事?当您只想提取每月价格和每日价格时,您的代码也会尝试查找每年和每周,为什么?@timgeb现在解决了这个问题。@RomanPerekhrest我只是想举个例子。我需要每年、每月、每周和每天的价格。好的,发布最终的预期结果。最后一个列表中的孤独的\n\n周是什么?你的代码试图同时查找每年和每周,为什么你只想提取每月价格和每日价格?timgeb现在解决了这个问题。@RomanPerekhrest我只是想举个例子。我需要每年,每月,每周和每天的价格。好的,张贴最终的预期结果