Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中检查字符串并获取具有特殊字符的单词_Python_Search - Fatal编程技术网

如何在python中检查字符串并获取具有特殊字符的单词

如何在python中检查字符串并获取具有特殊字符的单词,python,search,Python,Search,我有一根像 "A collection point is a fancy name for what is essentially a dumpster #Gazipur #issue #Garbage #Garbagecollection" 在这里,我只需要搜索带有“#”的单词,并将这些单词放入变量中 我尝试了很多方法 谢谢您可以使用reg-ex import re r = re.compile('#(.*?)\s+') m = r.search(str1) if m: hashtag

我有一根像

"A collection point is a fancy name for what is essentially a dumpster
#Gazipur #issue #Garbage #Garbagecollection"
在这里,我只需要搜索带有“#”的单词,并将这些单词放入变量中

我尝试了很多方法

谢谢

您可以使用reg-ex

import re
r = re.compile('#(.*?)\s+')
m = r.search(str1)
if m:
   hashtags = m.group(1)
编辑:

根据您的答案,将其修改为:

进口稀土

str1 = '#lol #loalsd asd'
r = re.compile('#(.*?)\s+')
m = r.findall(str1)
if m:
   hashtags = m
   print(hashtags)
您可以将列表理解与过滤器一起使用,如下所示:

>>> my_str = 'Gazipur #issue #Garbage #Garbagecollection'
>>> prefix = '#'

#                 filter words starting with prefix v
>>> [word for word in my_str.split() if word.startswith(prefix)]
['#issue', '#Garbage', '#Garbagecollection']
如果要删除每个单词的前缀,可以在列表理解表达式中对每个字符串进行切片,如下所示:

#           v slice string to remove the `prefix` 
>>> [word[len(prefix):] for word in my_str.split() if word.startswith(prefix)]
['issue', 'Garbage', 'Garbagecollection']

基于Akshay的答案,你可以:

import re

str1 = '#lol #loalsd asd'
r = re.compile('#(.*?)\s+')
m = r.findall(str1)
if m:
   hashtags = m
   print(hashtags)

hashtags是一个列表,因此您可以相应地访问它们。

请展示一些方法。策略:在空格上拆分,在单词上循环,定义“特殊字符”。@Nithin你能澄清一下你是否需要“#”符号以及要存储的单词吗?或者仅仅是单词,去掉散列符号?我已经尝试了所有答案,我得到了所有答案的相同输出,我想要感谢所有人的帮助me@code_byter谢谢你帮我我不需要这个symbol@Nithinsaikumar但你勾选了另一个答案:)没关系。如果需要,您可以使用我的,而不使用散列。我不确定,但我认为OP是在寻找没有hastag的单词。@code\u byter根据OP的注释“我只需要搜索带“#”的单词,并将这些单词放入变量”。我想OP想要我所做的:)哇,我想我们的解释是不同的。那我们问问OP吧。