【问题标题】:splitting merged words in python在python中拆分合并的单词
【发布时间】:2011-03-20 03:06:11
【问题描述】:

我正在处理一个文本,其中所有“\n”都已被删除(它将两个词合并为一个,例如“我喜欢香蕉,这是一个新行。还有一个。”)我想做的事现在是告诉 Python 查找小写字母后跟大写字母/标点符号后跟大写字母的组合并插入空格。

我认为使用 reg 会很容易。表达式,但它不是 - 我找不到“插入”函数或任何东西,字符串命令似乎也没有帮助。我该怎么做呢? 任何帮助将不胜感激,我在这里感到绝望......

谢谢,帕特里克

【问题讨论】:

    标签: python


    【解决方案1】:

    尝试以下方法:

    re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", your_string)
    

    例如:

    import re
    lines = "I like bananasAnd this is a new line.And another one."
    print re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", lines)
    # I like bananas And this is a new line. And another one.
    

    如果要插入换行符而不是空格,请将替换更改为 r"\1\n\2"

    【讨论】:

      【解决方案2】:

      使用re.sub,您应该能够创建一个模式,该模式可以抓取一个小写字母和一个大写字母,并将它们替换为相同的两个字母,但中间有一个空格:

      import re
      re.sub(r'([a-z][.?]?)([A-Z])', '\\1\n\\2', mystring)
      

      【讨论】:

      • 这似乎产生了以下内容:我喜欢香蕉\1\n\2nd 这是一个新的 lin\1\n\2nd 另一个。要解决此问题,请将替换部分更改为 \1\n\2
      • Tom,我想您在尝试时可能不小心在我的示例中的第二个字符串常量前面放了一个r 字符。 Python 字符串'\\1\n\\2' 是一系列字符\1<NEWLINE>\2
      【解决方案3】:

      您正在寻找sub 函数。有关文档,请参阅 http://docs.python.org/library/re.html

      【讨论】:

        【解决方案4】:

        嗯,有趣。您可以使用正则表达式将文本替换为sub() function

        >>> import re
        >>> string = 'fooBar'
        >>> re.sub(r'([a-z][.!?]*)([A-Z])', r'\1 \2', string)
        'foo Bar'
        

        【讨论】:

        • 老兄。美元符号不是您插入组的方式。 :-)
        • @Brandon:是的,刚刚意识到,谢谢。仍在考虑 Perl ;-)
        【解决方案5】:

        如果除了句首之外真的没有大写字母,那么循环遍历字符串可能是最简单的。

        >>> import string
        >>> s = "a word endsA new sentence"
        >>> lastend = 0
        >>> sentences = list()
        >>> for i in range(0, len(s)):
        ...    if s[i] in string.uppercase:
        ...        sentences.append(s[lastend:i])
        ...        lastend = i
        >>> sentences.append(s[lastend:])
        >>> print sentences
        ['a word ends', 'A new sentence']
        

        【讨论】:

          【解决方案6】:

          这是另一种方法,它避免使用正则表达式并且不使用任何导入的库,只是内置...

          s = "I like bananasAnd this is a new line.And another one."
          with_whitespace = ''
          last_was_upper = True
          for c in s:
              if c.isupper():
                  if not last_was_upper:
                      with_whitespace += ' '
                  last_was_upper = True
              else:
                  last_was_upper = False
              with_whitespace += c
          
          print with_whitespace
          

          产量:

          I like bananas And this is a new line. And another one.
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-04-11
            • 2012-09-24
            • 1970-01-01
            • 1970-01-01
            • 2013-05-31
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多