首页 > 解决方案 > 如果消息内容有一个数字后跟一个字母,那么做一些事情

问题描述

我有一个脚本可以抓取一些转售服务器。有些人以 2.1k 的格式写价格,我遇到的问题是我查找字母“k”并在价格中使用它,但它会查找带有字母“k”的单词,例如列表将显示“ Take 2.1k for my product” 由于字母“k”,价格会显示为“Taking”。我将如何确保它只查找后跟字母 K 的数字?

        check1 = False
        check2 = True
        for x in message.content.lower():
            print(x)
            if x == "k":
                check1 = True
            elif x == "$":
                check1 = True
            elif x == "£":
                check1 = True
        if check1 and check2: #both success so must be correct
            print("Is not a dm and includes a price")
            split_message = message.content.split(" ")
            price = None
            for x in split_message:
                if "$" in x:
                    #if "/" not in x:
                        price = x
                elif "£" in x:
                    #if "/" not in x:
                        price = x
                elif "k" in x:
                    #if "/" not in x:
                        price = x

更新:

if check1 and check2: #both success so must be correct
            print("Is not a dm and includes a price")
            split_message = message.content.split(" ")
            messageNoBold = message.content.replace('**','')
            price = None
            thePrice = re.findall("\d+(\.\d+)?[kK]", split_message)
            for x in thePrice:
                
                if "$" in x:
   
                        price = x
                        
                elif "£" in x:
                    
                        price = x
                        
                elif "k" in x:
                    
                        price = x
                        
            print(price)

回报 -

return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

标签: python

解决方案


你可以用正则表达式来做到这一点:

re.findall("\d+(\.\d+)?[kK]", text)

谢谢 Abion47


推荐阅读