【问题标题】:re.split() vs str.split() in pythonpython 中的 re.split() 与 str.split()
【发布时间】:2018-02-11 20:41:25
【问题描述】:

我遇到过这个应该标记给定句子的函数

def basic_tokenizer(sentence):
    words = []
    for space_separated_fragment in sentence.strip().split():
        words.extend(re.split(" ", space_separated_fragment))
    return [w for w in words if w]

在我看来, sentence.strip().split() 应该已经足够了,但随后使用了 re.split(),然后在返回中甚至 [w for w in words if w]

我想知道这可能是什么原因?一个通过所有三个都不同的例子将不胜感激

【问题讨论】:

  • 如果是 re.split(" ") 进行实际拆分,或者如果 for 循环结束 .split(" ") 而不仅仅是 .split(),那么 [w for w in words if w] 将是有意义的,因为可能存在words 中的空字符串。仅供参考。
  • @NathanVērzemnieks 多个连续空格都被str.split()视为一个空格
  • 是的,如果你在没有参数的情况下分割 - 但如果你只在“”上分割,则不会。

标签: python python-3.x split


【解决方案1】:

整个函数可以简化为:

def basic_tokenizer(sentence):
    return sentence.split()

原因:

  • sentence.strip().split() 已经去掉了结尾的空格,并在空白处分割,没有必要遍历结果列表和 extend-ing words 列表 再次按空格分割 (words.extend(re.split(" ", space_separated_fragment)))

  • 此外,在[w for w in words if w] 中,if w 检查也是多余的,因为不存在虚假元素(因为所有字符串都是非空字符串)

【讨论】:

  • 第二次使用spilled 完全是多余的——space_separated_fragment 保证其中没有任何空格,因为它是sentence().strip().split() 的结果。
  • 这是来自斯坦福在 cs224n 中提供的 assignment 4 的起始代码。如果您仍然认为 re.split() 的使用完全是多余的,我是否可以建议您怀疑您的答案并确认一下?
  • 另外,为什么“返回 [w for w in words if w]”。 “回话”似乎是该做的事
  • 没有必要使用strip() - 当与split() 一起使用时它完全是多余的(即没有参数)。
  • @ekhumoro 是的。已编辑。
猜你喜欢
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多