【问题标题】:How to check a string and get the words with the special characters in python [closed]如何在python中检查字符串并获取带有特殊字符的单词[关闭]
【发布时间】:2017-06-30 06:48:41
【问题描述】:

我有一个类似

的字符串
"A collection point is a fancy name for what is essentially a dumpster
#Gazipur #issue #Garbage #Garbagecollection"

这里我只需要搜索带有“#”的单词并将这些单词放入变量中

我尝试了很多方法。

谢谢

【问题讨论】:

  • 请展示一些方法。策略:空格分割,单词循环,定义“特殊字符”。
  • @Nithin 您能否澄清一下是否需要“#”符号以及要存储的单词?还是只是单词,去掉井号?
  • 我已经尝试了所有的答案,我得到了所有我想要的答案的相同输出,感谢大家对我的帮助
  • @code_byter 感谢帮助我,我不需要“#”符号
  • @Nithinsaikumar 但你勾选了另一个答案:) 没关系。如果你需要没有哈希,你可以使用我的。

标签: python search


【解决方案1】:

您可以使用带有string.startswith 过滤器的列表理解

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

如果您想从每个单词中删除 prefix,您可以将 list comprehension 表达式中的每个字符串切片为:

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

【讨论】:

  • 我不确定,但我认为 OP 正在寻找没有标签的单词。
  • @code_byter 根据 OP 的评论 “我需要仅搜索带有“#”的单词并将这些单词放入变量中”。我认为 OP 想要我所做的 :)
  • 哇,我们的解释不一样了,我猜。那我们问问OP吧。
【解决方案2】:

基于 Akshay 的回答,您可以这样做:

import re

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

主题标签是一个列表,因此您可以相应地访问它们。

【讨论】:

    【解决方案3】:

    你可以使用 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 2021-03-03
      • 2013-11-27
      • 2021-09-30
      相关资源
      最近更新 更多