簡體   English   中英

從注釋中刪除所有內容,但某些字符串除外

[英]Remove everything from comment except certain string

因此,我為Reddit制作了一個機器人,該機器人偵聽了一個特定的字符串,該字符串將機器人付諸行動。 好叫那個字符串,“ !callme ”。 使用此漫游器時,必須在呼叫字符串后提供一個數字,例如“ !callme 1234 ”。

目前,我已將該機器人設置為刪除“ !callme ”和字符串中的空格,如果此后還存在其他任何內容,它將發布“失敗”注釋並告訴用戶重試。 我想要做的是有它除了 “后的數字串的注釋去掉所有的一切!callme ”的字符串。 我需要它,因為它在數學運算中使用數字,並且如果最終值不是數字,則它會失敗並告訴用戶輸入錯誤。

例如:“ !callme 12345 ”將起作用並發布正確的注釋,但是“ !callme helloworld ”將失敗並發布注釋以告訴他們正確的格式。

我想跳過該步驟,並除去“!callme”字符串后面的數字字符串以外的所有內容。 基本上,如果用戶在調用機器人之前寫了一個句子,它將失敗。 我想改變那個。

我現在的代碼在下面,用於當前工作區。

g = comment.body
        pattern = re.compile(r'\s+')
        g = re.sub(pattern, '', g)
        g = g.replace('!callme', '')
        if g.isdigit():
            g = int(g)
        else:
            bad comment here
            data_entry(com_id, com_auth, 1)
            print("Bad comment found! Posting reply to comment " + comment.id + "!")
        if isinstance(g, int):
            cp = float(g / 100)
            pa = float(cp / 10)
            good comment here

還有其他帶有注釋的try語句,但這無關緊要。

我該怎么做呢? 另外,如果此處的代碼不是最佳選擇,請隨時糾正我。

如果我正確地回答了您的問題,這樣的事情適合嗎?

g = "!callme XXX"
pat = re.compile(r'[0-9]+')
num = re.findall(pat, g) # num = []
g = "!callme 1234"
num = re.findall(pat, g) # num = '1234', now you could int(num)

或者您可以使用更精確的正則表達式,例如

g = "!callme   1234" 
pat = re.compile(r'(\!callme[ ]*)([0-9]+)')
m = re.search(pat, g)
# and go directly to group 2 which should be the num
print m.group(2) # this prints 1234, then int(m.group(2))

在這里,我定義了兩個組,一個用於callme部分,另一個用於數字部分

這應該與您想要的號碼相匹配。

pattern = re.compile(".*!callme +(\d+).*")
result = re.findall(pattern, g)
if result:
    g = int(result[0])

模式說明: .*!callme +(\\d+).*
.*匹配!callme之前的任何內容
+!callme之后至少匹配一個空格
(\\d+)至少匹配一位數字
.*匹配之后的任何字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM