如何在Python中查找字符串中的x

发布于 2024-10-07 09:34:58 字数 173 浏览 11 评论 0原文

我想知道如何在字符串中找到您不知道是什么的字符串。我正在编写一个 IRC 机器人,我需要这个功能。我希望能够写:

!问候格雷格

,然后我的机器人应该说“嗨,格雷格!”。所以问候之后的内容是可变的。如果我写!问候马修,它会说“嗨,马修!”。 这可能吗?

多谢。

安德赛

I was wondering how to go about finding a string you don't know what is, in a string. I am writing an IRC bot and i need this function. I want to be able to write:

!greet Greg

and then my bot is supposed to say "Hi, Greg!". So what comes after greet is variable. And if i wrote !greet Matthew it would say "Hi, Matthew!".
Is this possible?

Thanks a lot.

Andesay

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

绅刃 2024-10-14 09:34:58
if command.lower().startswith('!greet '):
    put('Hi, ' + command[7:].strip() + '!')

'!greet Greg' -> [ put()s 'Greg' ]
'!Greet  Fred ' -> [ put()s 'Fred' ]
'!hello John' -> [ nothing ]
if command.lower().startswith('!greet '):
    put('Hi, ' + command[7:].strip() + '!')

'!greet Greg' -> [ put()s 'Greg' ]
'!Greet  Fred ' -> [ put()s 'Fred' ]
'!hello John' -> [ nothing ]
过期情话 2024-10-14 09:34:58
import re
...
input = '!greet Greg'
m = re.match(r'!greet\s+(.*)', input)
if m:
    print 'Hi, %s!' % m.group(1)
import re
...
input = '!greet Greg'
m = re.match(r'!greet\s+(.*)', input)
if m:
    print 'Hi, %s!' % m.group(1)
舂唻埖巳落 2024-10-14 09:34:58

如果您计划为您的机器人添加更多复杂性,我建议使用如下正则表达式:

首先定义您的机器人可能需要的功能。

def greet_user(name):
    print 'Hello, %s' % name

然后定义模式和命令字典:

import re
pattern = re.compile(r'!(?P<command>\w+)\s*(?P<args>\w*)')
commands = {'greet': greet_user}

现在您只需使用用户输入和适当的函数调用 pattern.match()

m = pattern.match(string)
commands.get(m.group('command'))(m.group('args'))

如果用户输入无效命令,则会引发 TypeError 。

现在,您只需编辑 commands-dict 即可添加任何功能。

If you plan on adding more complexity to your bot, i would suggest using regular expressions like this:

At first you define the functions your bot may need.

def greet_user(name):
    print 'Hello, %s' % name

Then you define the pattern and a dict of commands:

import re
pattern = re.compile(r'!(?P<command>\w+)\s*(?P<args>\w*)')
commands = {'greet': greet_user}

Now you just have to call pattern.match() with the user input and the appropriate function:

m = pattern.match(string)
commands.get(m.group('command'))(m.group('args'))

If a user enters an invalid command, a TypeError is thrown.

Now you can add any function just by editing the commands-dict.

世界等同你 2024-10-14 09:34:58

很简单:

>>> import re
>>> m = re.search(r"!greet (?P<name>.+)", "!greet Someone")
>>> m.group("name")
'Someone'

It's simple:

>>> import re
>>> m = re.search(r"!greet (?P<name>.+)", "!greet Someone")
>>> m.group("name")
'Someone'
蹲墙角沉默 2024-10-14 09:34:58

如果问候语中是“Greg”:
doSomething("Hi Greg")

关键是字符串采用 in 运算符

if "Greg" in greet:
doSomething("Hi Greg")

the key is that strings take the in operator

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文