![](/img/trans.png)
[英]If value is equal with a key in the given dictionary, how can I append to the key of the said value the value of the first key
[英]How can I extract the value of a given key?
我如何从这个字符串中提取放弃('type=weaksubj len=1 word1=abandonment pos1=noun stemmed1=n priorpolarity=negative')
?
一种可能的方法是 -
(这是一个python代码)
regexp = re.findall("word1=[a-zA-Z0-9]*",string)
但结果我得到
['word1=abandonment']
我怎样才能修改正则表达式,这样我就不会得到“word1”的结果。 可以使用 python 中的任何字符串函数删除“word1” ,但我希望修改我的正则表达式。
您需要将要返回的组括在括号中,然后查找组(在本例中为 0)。
res= re.search("word1=([a-zA-Z0-9]+?)",mystring)
whatyourelookingfor = res.group[0]
如果键值对是唯一的,并且始终具有相同的格式,则可以通过拆分和创建字典来获得所需的结果,而无需正则表达式:
s = 'type=weaksubj len=1 word1=abandonment pos1=noun stemmed1=n priorpolarity=negative'
dct = dict([x.split("=") for x in s.split()])
print(dct) # => {'stemmed1': 'n', 'len': '1', 'word1': 'abandonment', 'priorpolarity': 'negative', 'type': 'weaksubj', 'pos1': 'noun'}
print(dct['word1']) # => abandonment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.