【问题标题】:Extracting all full words between in a certain amount of characters提取一定数量字符之间的所有完整单词
【发布时间】:2012-07-05 09:45:55
【问题描述】:

我想提取一段文本并从给定数量的字符中提取尽可能多的单词。我可以使用哪些工具/库来完成此操作?

例如,在given 文本块中:

Have you managed to get your hands on Nikon's elusive D4 full-frame DSLR? 
It should be smooth sailing from here, with the occasional firmware update being 
your only critical acquisition going forward. D4 firmware 1.02 brings a handful of 
minor fixes, but if you're in need of any of the enhancements listed below, it's 
surely a must have:

如果我将它分配给一个字符串,然后生成 string = string[0:100],那将得到前 100 个字符,但“sailing”这个词将被截断为“sailin”,我想要'sailing' 之前或之后的空格将被截断的文本。

【问题讨论】:

    标签: python string


    【解决方案1】:

    使用正则表达式:

    >>> re.match(r'(.{,100})\W', text).group(1)
    "Have you managed to get your hands on Nikon's elusive D4 full-frame DSLR? It should be smooth"
    

    此方法可让您搜索单词之间的任何标点符号(不仅是空格)。 它将匹配 100 个或更少的字符。

    要处理小字符串,下面的正则表达式更好:

    re.match(r'(.{,100})(\W|$)', text).group(1)
    

    【讨论】:

    • @Antimony 不是这个。它毫无疑问地表示:在非单词字符之前最多匹配 100 个字符。
    • 这只有在你熟悉正则表达式语法的情况下才是正确的。
    • @Antimony:花一两个小时了解正则表达式的语法。你会很高兴你做到了。正确使用时非常强大的工具(就像这里...)
    【解决方案2】:

    如果你真的只想在空格上打断字符串,那么使用这个:

    my_string = my_string[:100].rsplit(None, 1)[0]
    

    但请记住,您实际上可能想要的不仅仅是空格。

    【讨论】:

    • +1:也很好地使用了rsplit。作为一个前 Perl 人,正则表达式对我来说更明显。
    【解决方案3】:

    这将在前 100 个字符的最后一个空格处将其截断。

    lastSpace = string[:100].rfind(' ')
    string = string[:lastSpace] if (lastSpace != -1) else string[:100]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多