【问题标题】:Python line.split to include a whitespacePython line.split 包含一个空格
【发布时间】:2012-11-23 18:53:02
【问题描述】:

如果我有一个字符串并想返回一个包含空格的单词,该怎么做?

例如,我有:

line = 'This is a group of words that include #this and @that but not ME ME'

response = [ word for word in line.split() if word.startswith("#") or  word.startswith('@')  or word.startswith('ME ')]

print response ['#this', '@that', 'ME']

所以 ME ME 因为空白而没有被打印出来。

谢谢

【问题讨论】:

  • 你实际想要的输出是什么?
  • 程序如何知道 ME ME 是一个包含空格的单词而不是两个单词? (一个单词怎么可能包含空格?)
  • ME ME 不是一个词,而是一个前缀(ME),然后是空格,然后是词(ME)。我希望程序能够全部完成。抱歉没有更清楚。

标签: python regex python-2.7


【解决方案1】:

你可以保持简单:

line = 'This is a group of words that include #this and @that but not ME ME'

words = line.split()

result = []

pos = 0
try:
    while True:
        if words[pos].startswith(('#', '@')):
            result.append(words[pos])
            pos += 1
        elif words[pos] == 'ME':
            result.append('ME ' + words[pos + 1])
            pos += 2
        else:
            pos += 1
except IndexError:
    pass

print result

只有在实践中证明速度太慢时才考虑速度。

【讨论】:

    【解决方案2】:

    来自 python 文档:

    string.split(s[, sep[, maxsplit]]):返回字符串s的单词列表。如果可选第二个 参数 sep 不存在或无,单词由任意分隔 空白字符字符串(空格、制表符、换行符、回车符、 换页)。

    所以你的错误首先是调用拆分。

    打印 line.split() ['this', 'is', 'a', 'group', 'of', 'words', 'that', 'include', '#this', 'and', '@that', 'but' , '不', '我', '我']

    我建议使用re 来分割字符串。使用 re.split(pattern, string, maxsplit=0, flags=0)

    【讨论】:

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