在Python中连接列表中的不完整句子

时间:2018-03-22 23:11:29

标签: python list concatenation string-concatenation

我有一个包含完整和不完整句子的列表。完整句子以sinon.stub(userStub, 'findOne').resolves( {toJSON: sinon.stub().returns(data)} ); .?终止。如何遍历列表中的元素并加入不完整的句子? 例如,

输入:

!

期望的输出:

myList = ['My first','sentence is incomplete.','Hold on.','Is the second complete?','The third','might not be!','Thanks.','Really appreciate.']

2 个答案:

答案 0 :(得分:1)

这是一种使用collections.defaultdict的强力方法。

from collections import defaultdict

myList = ['My first','sentence is incomplete.','Hold on.','Is the second complete?',
          'The third','might not be!','Thanks.','Really appreciate.']

d = defaultdict(list)

idx = 0
for j in myList:
    d[idx].append(j)
    if any(j.endswith(k) for k in ('.', '!', '?')):
        idx += 1

sentences = [' '.join(v) for _, v in sorted(d.items())]

结果:

['My first sentence is incomplete.',
 'Hold on.',
 'Is the second complete?',
 'The third might not be!',
 'Thanks.',
 'Really appreciate.']

答案 1 :(得分:1)

The concatenation of the incomplete sentences is the easy part, just use the "+" symbol to join the sentences for example, use myList[0]+myList[1] to get 'My first sentence is incomplete.' You should erase the used elements from the list to not have any problems later. to verify which ones to add, you should use a while loop like this:

while (myList!=[]):
    index=0
    if myList[index][-1]=="." or myList[index][-1]=="?" or myList[index][-1]=="!" : #checks if the last element of the string is a . ? or !
        #make a function to concatenate the list elements from myList[0] to myList[index],and delete said elements from the original list, remember to reset index to 0 and repeaat process