在将某些关键字提到列表中之后切片

时间:2016-04-10 13:39:46

标签: python string list

我是python的新手,我遇到了问题。我想要做的是,我有一个包含两个人之间对话的字符串:

str = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"

我想使用dylankid和senpai作为名称从字符串创建2个列表:

dylankid = [ ]
senpai = [ ]

这里是我挣扎的地方,在里面列表dylankid我想把'dylankid'后面的所有单词放在字符串中但是在下一个'dylankid'或'senpai'之前 senpai列表同样如此 所以它看起来像这样

dylankid = ["random words", "random words", "random words"]
senpai = ["random words", "random words", "random words"]    

dylankid包含来自dylankid的所有消息,反之亦然。

我已经研究过切片并使用split()re.compile(),但是我无法想出一种方法来指定开始切片和停止的位置。

希望很清楚,任何帮助都会受到赞赏:)

3 个答案:

答案 0 :(得分:4)

以下代码将创建一个dict,其中键是人,值是消息列表:

from collections import defaultdict
import re

PATTERN = '''
    \s*                         # Any amount of space
    (dylankid|senpai)           # Capture person
    :\s                         # Colon and single space
    (.*?)                       # Capture everything, non-greedy
    (?=\sdylankid:|\ssenpai:|$) # Until we find following person or end of string
'''
s = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
res = defaultdict(list)
for person, message in re.findall(PATTERN, s, re.VERBOSE):
    res[person].append(message)

print res['dylankid']
print res['senpai']

它将产生以下输出:

['*random words*', '*random words*']
['*random words*', '*random words*']

答案 1 :(得分:2)

您可以使用groupby,使用__contains__

拆分单词和分组
s = "dylankid: *random words d* senpai: *random words s* dylankid: *random words d*  senpai: *random words s*"
from itertools import groupby

d = {"dylankid:": [], "senpai:":[]}

grps = groupby(s.split(" "), d.__contains__)

for k, v in grps:
    if k:
        d[next(v)].append(" ".join(next(grps)[1]))
print(d)

输出:

{'dylankid:': ['*random words d*', '*random words d*'], 'senpai:': ['*random words s*', '*random words s*']}

每次我们在dict中获取名称时,我们会使用next(v)的名称,使用str.join获取下一个名称的下一个单词组,以便加入一个字符串。

如果您的名字后面没有任何单词,您可以使用空列表作为下次通话的默认值:

s = "dylankid: *random words d* senpai: *random words s* dylankid: *random words d*  senpai: *random words s* senpai:"
from itertools import groupby

d = {"dylankid:": [], "senpai:":[]}
grps = groupby(s.split(" "), d.__contains__)

for k, v in grps:
    if k:
        d[next(v)].append(" ".join(next(grps,[[], []])[1]))
print(d)

更大字符串的一些时间:

In [15]: dy, sn = "dylankid:", " senpai:"

In [16]: t = " foo " * 1000

In [17]: s = "".join([dy + t + sn + t for _ in range(1000)])

In [18]: %%timeit
   ....: d = {"dylankid:": [], "senpai:": []}
   ....: grps = groupby(s.split(" "), d.__contains__)
   ....: for k, v in grps:
   ....:     if k:
   ....:         d[next(v)].append(" ".join(next(grps, [[], []])[1]))
   ....: 
1 loop, best of 3: 376 ms per loop

In [19]: %%timeit
   ....: PATTERN = '''
   ....:     \s*                         # Any amount of space
   ....:     (dylankid|senpai)           # Capture person
   ....:     :\s                         # Colon and single space
   ....:     (.*?)                       # Capture everything, non-greedy
   ....:     (?=\sdylankid:|\ssenpai:|$) # Until we find following person or end of string
   ....: '''
   ....: res = defaultdict(list)
   ....: for person, message in re.findall(PATTERN, s, re.VERBOSE):
   ....:     res[person].append(message)
   ....: 
1 loop, best of 3: 753 ms per loop

两者都返回相同的输出:

In [20]: d = {"dylankid:": [], "senpai:": []}

In [21]: grps = groupby(s.split(" "), d.__contains__)

In [22]: for k, v in grps:
           if k:                                        
                d[next(v)].append(" ".join(next(grps, [[], []])[1]))
   ....:         

In [23]: PATTERN = '''
   ....:     \s*                         # Any amount of space
   ....:     (dylankid|senpai)           # Capture person
   ....:     :\s                         # Colon and single space
   ....:     (.*?)                       # Capture everything, non-greedy
   ....:     (?=\sdylankid:|\ssenpai:|$) # Until we find following person or end of string
   ....: '''

In [24]: res = defaultdict(list)

In [25]: for person, message in re.findall(PATTERN, s, re.VERBOSE):
   ....:         res[person].append(message)
   ....:     

In [26]: d["dylankid:"] == res["dylankid"]
Out[26]: True

In [27]: d["senpai:"] == res["senpai"]
Out[27]: True

答案 2 :(得分:1)

这可以收紧,但应该很容易扩展到更多的用户名。

from collections import defaultdict

# Input string
all_messages = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"

# Expected users
users = ['dylankid', 'senpai']

starts = {'{}:'.format(x) for x in users}
D = defaultdict(list)
results = defaultdict(list)

# Read through the words in the input string, collecting the ones that follow a user name
current_user = None
for word in all_messages.split(' '):
    if word in starts:
        current_user = word[:-1]
        D[current_user].append([])
    elif current_user:
        D[current_user][-1].append(word)

# Join the collected words into messages
for user, all_parts in D.items():
    for part in all_parts:
        results[user].append(' '.join(part))

结果是:

defaultdict(
    <class 'list'>,
    {'senpai': ['*random words*', '*random words*'],
    'dylankid': ['*random words*', '*random words*']}
)