【问题标题】:Better way to control granularity of splitting string by word/token or character更好的方法来控制按单词/标记或字符分割字符串的粒度
【发布时间】:2021-04-19 00:54:13
【问题描述】:

我有一个常见的操作,允许用户使用“word”或“char”作为单位,我一直这样做:

def split(s, unit):
    return s.split() if unit == 'word' else list(s)

用法:

>>> foo = "this is a foo bar sentence"
>>> split(foo, 'word')
['this', 'is', 'a', 'foo', 'bar', 'sentence']
>>> split(foo, 'char')
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'f', 'o', 'o', ' ', 'b', 'a', 'r', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

有没有一种简单/更好的方法来创建一个根据单词(由str.split 定义)和字符分割输入字符串的函数?

【问题讨论】:

    标签: python string split nlp token


    【解决方案1】:

    这取决于你想要做什么。我假设您需要一个函数,如果输入有多个单词,则将其拆分为单词,否则拆分为字符:

    def split(s):
        l = s.split()
        return l if len(l) > 1 else list(s)
    

    如果您有其他想法,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多