2013-02-17 50 views
0

我試圖從具有來自不同列表的#(哈希標籤)的「句子」附加列表(空)。 目前我的代碼給了我一個列表中涉及元素總數的新列表,而不是單個句子。用reg添加列表。表達式

的代碼片段如下

import re 

old_list = ["I love #stackoverflow because #people are very #helpful!","But I dont #love hastags", 
"So #what can you do","Some simple senetnece","where there is no hastags","however #one can be good"] 

new_list = [ ] 


for tt in range(0,len(s)): 
    for ui in s: 
     if bool(re.search(r"#(\w+)",s[tt])) == True : 
      njio.append(s[tt]) 

給請讓我知道如何追加僅單句。

回答

2

我不知道你想要什麼樣的輸出,但這將保留原句與其匹配的集主題標籤一起:

>>> import re 
>>> old_list = ["I love #stackoverflow because #people are very #helpful!","But I dont #love hastags", 
... "So #what can you do","Some simple senetnece","where there is no hastags","however #one can be good"] 
>>> hash_regex = re.compile('#(\w+)') 
>>> [(hash_regex.findall(l), l) for l in old_list] 
[(['stackoverflow', 'people', 'helpful'], 'I love #stackoverflow because #people are very #helpful!'), (['love'], 'But I dont #love hastags'), (['what'], 'So #what can you do'), ([], 'Some simple senetnece'), ([], 'where there is no hastags'), (['one'], 'however #one can be good')] 
+0

@sberry ......如何關閉這個問題。 – LonelySoul 2013-02-22 19:39:22

+0

只需點擊左側我答案旁邊的複選標記。 – sberry 2013-02-24 02:17:07