【问题标题】:How to split string by space and treat special characters as a separate word in Python?如何按空格分割字符串并将特殊字符视为Python中的单独单词?
【发布时间】:2016-05-25 18:44:35
【问题描述】:

假设我有一个字符串,

"I want that one, it is great."

我想把这个字符串拆分成

["I", "want", "that", "one", ",", "it", "is", "great", "."]

",.:;" 等特殊字符以及可能的其他字符视为单独的单词。

在 Python 2.7 中是否有任何简单的方法可以做到这一点?

更新

例如"I don't.",应该是["I", "don", "'", "t", "."]。理想情况下,它适用于非英语标点符号,例如 ؛ 等。

【问题讨论】:

  • 你会如何处理像"don't"这样的词?你有['don', ''', 't']吗?
  • @RNar 是的,正确。
  • [c for c in re.split('(\W+)', s) if c.strip() != '']
  • 我在 Python 方面不是很有经验,但在 C# 中,您只需将 string.Split() 方法与包含空格和特殊字符的字符数组一起使用

标签: python python-2.7


【解决方案1】:
In [70]: re.findall(r"[^,.:;' ]+|[,.:;']", "I want that one, it is great.")
Out[70]: ['I', 'want', 'that', 'one', ',', 'it', 'is', 'great', '.']

In [76]: re.findall(r"[^,.:;' ]+|[,.:;']", "I don't.")
Out[76]: ['I', 'don', "'", 't', '.']

正则表达式 [^,.:;' ]+|[,.:;'] 匹配(除 ,.:;' 或文字空格之外的 1 个或多个字符)或(文字字符 @987654332 @、.:;')。


或者,使用regex module,您可以使用[:punct:] 字符类轻松扩展它以包含所有punctuation and symbols

In [77]: import regex

在 Python2 中:

In [4]: regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u"""A \N{ARABIC SEMICOLON} B""")
Out[4]: [u'A', u'\u061b', u'B']

In [6]: regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u"""He said, "I don't!" """)
Out[6]: [u'He', u'said', u',', u'"', u'I', u'don', u"'", u't', u'!', u'"']

在 Python3 中:

In [105]: regex.findall(r"[^[:punct:] ]+|[[:punct:]]", """A \N{ARABIC SEMICOLON} B""")
Out[105]: ['A', '؛', 'B']

In [83]: regex.findall(r"[^[:punct:] ]+|[[:punct:]]", """He said, "I don't!" """)
Out[83]: ['He', 'said', ',', '"', 'I', 'don', "'", 't', '!', '"']

请注意,如果您希望 [:punct:] 匹配 unicode 标点符号或符号,请将 unicode 作为第二个参数传递给 regex.findall,这一点很重要。

在 Python2 中:

import regex
print(regex.findall(r"[^[:punct:] ]+|[[:punct:]]", 'help؛'))
print(regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u'help؛'))

打印

['help\xd8\x9b']
[u'help', u'\u061b']

【讨论】:

  • 第二种解决方案是否适用于非英语标点符号,例如 ،؛
  • 确实如此。当应用于 unicode 时,[:punct:] 匹配 Punctuation \p{P} or Symbol \p{S} category 中的任何 unicode 字符。另请参阅regular-expressions.info/posixbrackets.html
  • 一切顺利。但是正则表达式在这个help؛ 上失败了,输出只是相同的字符串。有什么想法吗?
  • 您是否将unicode 作为第二个参数传递给regex.findall?我在上面添加了一个示例,显示了当传递str(例如'help؛')而不是unicode(例如u'help؛')时会发生什么。如果这是问题所在,那么您可以通过使用适当的编码(例如 'help؛'.decode('utf-8') )解码 str 以生成 unicode 来修复它。
  • 那行得通。非常感谢。你怎么能同时如此博学、耐心和风趣(我读过你的“关于我”)?
【解决方案2】:

请参阅here 了解类似问题。那里的答案也适用于你:

import re
print re.split('(\W)', "I want that one, it is great.")
print re.split('(\W)', "I don't.")

您可以使用过滤器删除re.split 返回的空格和空字符串:

s = "I want that one, it is great."
print filter(lambda _: _ not in [' ', ''], re.split('(\W)', s))

【讨论】:

    【解决方案3】:

    您可以使用正则表达式和简单的列表推导来执行此操作。正则表达式会抽出单词和分隔标点符号,列表推导会删除空格。

    import re
    s = "I want that one, it is great. Don't do it."
    new_s = [c.strip() for c in re.split('(\W+)', s) if c.strip() != '']
    print new_s
    

    new_s 的输出将是:

    ['I', 'want', 'that', 'one', ',', 'it', 'is', 'great', '.', 'Don', "'", 't', 'do', 'it', '.']
    

    【讨论】:

    • 这很有希望,但有没有办法修剪字符串以避免", "中的多余空格
    • @M-T-A 是的,刚刚修复
    • @EoinS 我刚刚解决了这个问题
    【解决方案4】:

    我不知道有什么函数可以做到这一点,但你可以使用 for 循环。

    类似这样的: 词=“” 字长 = 0 对于范围内的 i(0,len(stringName)): 如果 stringName[i] != " ": 对于范围内的 x((i-wordLength),i): 单词 += 字符串名称[i] 字长 = 0 list.append(word) 词=“” 别的: 世界长度 = 字长 + 1 希望这行得通...抱歉,如果这不是最好的方法

    【讨论】:

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