我如何从以下内容中提取“摔跤”一词:
type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative
使用正则表达式?
谢谢
答案 0 :(得分:6)
问题不是很清楚,但我想这就是你要找的东西:
word1=(\w+)
您的比赛将在第1组。这是一些示例Python代码:
import re
yourstring = 'type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative'
m = re.search(r'word1=(\w+)', yourstring)
print m.group(1)
见codepad。一个更通用的解决方案:
import re
def get_attr(str, attr):
m = re.search(attr + r'=(\w+)', str)
return None if not m else m.group(1)
str = 'type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative'
print get_attr(str, 'word1') # wrestle
print get_attr(str, 'type') # weaksubj
print get_attr(str, 'foo') # None
也可在codepad
上找到答案 1 :(得分:2)
鉴于以下正则表达式......
/word1=(\w+)/
... $ 1或者您的第一场比赛是用您的语言进行的任何比赛都将进行摔跤。
答案 2 :(得分:0)
你的正则表达式会是这样的
/.*word1=(\w+)/
答案 3 :(得分:0)
使用:/word1=(\w+)/
答案 4 :(得分:0)
假设它总是以空格分隔
word1=([^ ]+)
然后你可以通过第一组比赛获得价值。
答案 5 :(得分:0)
当str.split看起来已经足够时,也许re是不必要的:
>>> s = "type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative"
>>> dd = dict(ss.split('=',1) for ss in s.split())
>>> dd['word1']
'wrestle'