Python正则表达式失败。。。。?

2024-06-02 08:12:02 发布

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

昨天我一直在尝试各种各样的解决办法,直到挂断电话睡觉。今天回来再看一眼。。。我仍然不明白我的正则表达式有什么问题。你知道吗

我试图搜索我的库存基于一个简单的名称,并返回一个项目索引和数量的项目,我有。你知道吗

例如,在我的清单(而不是刀)中,我可以在0索引处使用血腥的\u刀[9],脚本应该根据刀的查询返回9和0。你知道吗

代码:

import re

inventory = ["knife", "bottle[1]", "rope", "flashlight"]


def search_inventory(item):
    numbered_item = '.*' + item + '\[([0-9]*)\].*'
    print(numbered_item)                   #create regex statement
    regex_num_item = re.compile(numbered_item)
    print(regex_num_item)                  #compiled regex statement
    for x in item:
        match1 = regex_num_item.match(x)   #regex match....
        print(match1)                      #seems to be producing nothing.
        if match1:                         #since it produces nothing the code fails.
            num_item = match1.group()
            count = match1.group(1)
            print(count)
            index = inventory.index(num_item)
        else:                              #eventually this part will expand to include "item not in inventory"
            print("code is wrong")
        return count, index

num_of_item, item_index = search_inventory("knife")
print(num_of_item)
print(item_index)

输出:

.*knife\[([0-9]*)\].*
re.compile('.*knife.*\\[([0-9]*)\\].*')
None
code is wrong

有一件事我似乎不能很好地解决,那就是python在我的numbered_item变量中获取代码并在re.compile()函数中使用它。既然我已经有了必要的[]转义,为什么还要添加额外的转义呢。你知道吗

以前有人碰到过这样的事吗?你知道吗


Tags: 项目代码reindexcountcodeitemnum
1条回答
网友
1楼 · 发布于 2024-06-02 08:12:02

您的问题是:

 for x in item:

这就是“对于项目中的每个字符knife”。所以您的正则表达式是在k上运行的,然后是n,依此类推。你的正则表达式当然不会想要那样。如果您仍然想“看”,请添加打印x:

for x in item:
        print x                            #add this line
        match1 = regex_num_item.match(x)   #regex match....
        print(match1)                      #seems to be producing nothing.

您将看到它将打印项目的每个字母。这就是你在你的match1 = regex_num_item.match(x)中所要匹配的,所以很明显它不起作用。 您想迭代inventory。你知道吗

所以你想:

 for x in inventory:    #meaning, for every item in inventory

对你来说index重要吗?因为您可以将清单更改为字典,而不必使用regex:

inventory = {'knife':8, 'bottle':1, 'rope':1, 'flashlight':0, 'bloody_knife':1}

然后,如果你想找到每一个有knife这个词的项目,以及你有多少个:

for item in inventory:
    if "knife" in item:
        itemcount = inventory[item]           #in a dictionary, we get the 'value' of the key this way
        print "Item Name: " + item + "Count: " + str(itemcount)

输出:

Item Name: bloody_knife, Count: 1
Item Name: knife, Count: 8

相关问题 更多 >