【问题标题】:Find a repeating pattern in a list of strings在字符串列表中查找重复模式
【发布时间】:2012-11-07 19:45:38
【问题描述】:

我正在寻找一种方法来清除最长重复模式中的字符串。

我有一个大约 1000 个网页标题的列表,它们都有一个共同的后缀,即网站名称。

他们遵循这种模式:

['art gallery - museum and visits | expand knowledge',
 'lasergame - entertainment | expand knowledge',
 'coffee shop - confort and food | expand knowledge',
 ...
]

如何自动从它们的公共后缀" | expand knowledge" 中去除所有字符串?

谢谢!

编辑:抱歉,我说得不够清楚。 我事先没有关于" | expand knowledge" 后缀的信息。 我希望能够清除潜在公共后缀的字符串列表,即使我不知道它是什么。

【问题讨论】:

  • 您能稍微扩展一下您的要求吗?现在看起来好像你在要求一些需要一些疯狂的计算时间的东西。
  • @SamIam 我正在开发一个爬虫,需要对目标网站的 HTML 结构有最少的了解。我正在从 HTML 标记中抓取页面的标题。这个网站的所有页面都包含一个共同的模式(``|扩展知识``),我非常想摆脱它,以避免任何冗余。主要问题是我事先没有关于后缀的信息,因为爬虫会在多个网站上发布。

标签: python regex string


【解决方案1】:

如果您确定所有字符串都具有共同的后缀,那么这将解决问题:

strings = [
  'art gallery - museum and visits | expand knowledge',
  'lasergame - entertainment | expand knowledge']
suffixlen = len(" | expand knowledge")
print [s[:-suffixlen] for s in strings]    

输出:

['art gallery - museum and visits', 'lasergame - entertainment']

【讨论】:

    【解决方案2】:

    如果您确实知道要删除的后缀,您可以这样做:

    suffix = " | expand knowledge"
    
    your_list = ['art gallery - museum and visits | expand knowledge',
     'lasergame - entertainment | expand knowledge',
     'coffee shop - confort and food | expand knowledge',
    ...]
    
    new_list = [name.rstrip(suffix) for name in your_list]
    

    【讨论】:

      【解决方案3】:

      以下是在反转标题上使用os.path.commonprefix 函数的解决方案:

      titles = ['art gallery - museum and visits | expand knowledge',
       'lasergame - entertainment | expand knowledge',
       'coffee shop - confort and food | expand knowledge',
      ]
      
      # Find the longest common suffix by reversing the strings and using a 
      # library function to find the common "prefix".
      common_suffix = os.path.commonprefix([title[::-1] for title in titles])[::-1]
      
      # Strips all titles from the number of characters in the common suffix.
      stripped_titles = [title[:-len(common_suffix)] for title in titles]
      

      结果:

      ['艺术画廊 - 博物馆和参观', '激光游戏 - 娱乐', '咖啡店 - 舒适和食物']

      因为它自己找到共同的后缀,所以它应该适用于任何标题组,即使您不知道后缀。

      【讨论】:

      • @BalthazarRouberol 请注意,如果巧合,每个条目中的最后一个字母都相同,这也会返回最后一个字母。
      猜你喜欢
      • 2019-11-17
      • 2014-11-18
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多