使用reg附加列表表达

时间:2013-02-17 04:57:36

标签: python regex

我正在尝试使用"句子附加一个列表(null)"其中有#(Hashtags)来自不同的列表。 目前我的代码给了我一个新的列表,其中包含列表中涉及的元素总数的长度,而不是单个句子。

下面给出了代码段

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])

请告诉我如何仅追加单句。

1 个答案:

答案 0 :(得分: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')]