连接 Python 列表中的不完整序列
Concatenating incomplete setences from lists in Python
我有一个包含完整和不完整句子的列表。完整的句子以 .
、?
或 !
结束。如何遍历列表中的元素并加入不完整的句子?
例如,
输入:
myList = ['My first','sentence is incomplete.','Hold on.','Is the second complete?','The third','might not be!','Thanks.','Really appreciate.']
期望的输出:
myList = ['My first sentence is incomplete.','Hold on.','Is the second complete?','The third might not be!','Thanks','Really appreciate.']
这是一个 brute-force 使用 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.']
不完整句子的拼接是比较容易的部分,用“+”符号拼接句子例如用myList[0]+myList[1]得到'My first sentence is incomplete.' You should erase列表中使用的元素以后不会有任何问题。要验证要添加哪些,您应该使用这样的 while 循环:
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
我有一个包含完整和不完整句子的列表。完整的句子以 .
、?
或 !
结束。如何遍历列表中的元素并加入不完整的句子?
例如,
输入:
myList = ['My first','sentence is incomplete.','Hold on.','Is the second complete?','The third','might not be!','Thanks.','Really appreciate.']
期望的输出:
myList = ['My first sentence is incomplete.','Hold on.','Is the second complete?','The third might not be!','Thanks','Really appreciate.']
这是一个 brute-force 使用 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.']
不完整句子的拼接是比较容易的部分,用“+”符号拼接句子例如用myList[0]+myList[1]得到'My first sentence is incomplete.' You should erase列表中使用的元素以后不会有任何问题。要验证要添加哪些,您应该使用这样的 while 循环:
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