![](/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.