在python中的关键字之后查找单词 [英] Finding words after keyword in python

查看:207
本文介绍了在python中的关键字之后查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到出现在关键字之后的单词(由我指定并搜索),然后打印出结果.我知道我想使用正则表达式来做到这一点,而且我也尝试过这样做,就像这样:

I want to find words that appear after a keyword (specified and searched by me) and print out the result. I know that i am suppose to use regex to do it, and i tried it out too, like this:

import re
s = "hi my name is ryan, and i am new to python and would like to learn more"
m = re.search("^name: (\w+)", s)
print m.groups()

输出为:

"is"

但是我想获得名称"一词之后的所有单词和标点符号.

But I want to get all the words and punctuations that comes after the word "name".

推荐答案

除了使用正则表达式,您还可以(例如)使用

Instead of using regexes you could just (for example) separate your string with str.partition(separator) like this:

mystring =  "hi my name is ryan, and i am new to python and would like to learn more"
keyword = 'name'
before_keyword, keyword, after_keyword = mystring.partition(keyword)
>>> before_keyword
'hi my '
>>> keyword
'name'
>>> after_keyword
' is ryan, and i am new to python and would like to learn more'

不过,您必须分别处理不必要的空格.

You have to deal with the needless whitespaces separately, though.

这篇关于在python中的关键字之后查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆