2012-11-23 76 views
0

如果我有一个字符串,并希望返回一个包含空格的单词,它将如何完成?Python line.split包含一个空格

例如,我有:

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'] 

那么急!不打印它,因为空白。

由于

+0

你的实际期望输出是什么? – mgilson

+2

程序应该如何知道ME ME是一个包含空白而不是两个单词的单词? (一个单词怎么能包含一个空格?) –

+0

ME ME不是一个单词,而是它是一个前缀(ME),然后是空格,然后是单词(ME)。我希望程序能够全部选中。道歉不清楚。 – user94628

回答

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 

想想速度,只有当它被证明是太慢实践。

1

从Python文档:

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

因此,您的错误是第一次在呼叫拆分。

打印line.split() [ '这', '是', 'A', '基团', '的', '字', '该',“包括”, '#此', '和', '@that', '但是', '不是', '我', '我']

我建议使用re为分割字符串。使用re.split(模式,字符串,maxsplit = 0,旗帜= 0)