0

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

例如,我有:

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 因为空白而没有被打印出来。

谢谢

4

2 回答 2

1

来自 python 文档:

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

所以你的错误首先是呼吁拆分。

print line.split() ['This', 'is', 'a', 'group', 'of', 'words', 'that', 'include', '#this', 'and', '@那','但是','不是','我','我']

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

于 2012-11-23T19:26:35.027 回答
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

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

于 2012-11-23T20:24:14.733 回答