gpt4 book ai didi

python - 将关键字值添加到下一行,直到找到下一个关键字 - Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:18 24 4
gpt4 key购买 nike

比如说,我有一个这样的值列表,

["Started with no key words",
PCC WITH NOTHING,
ABB,CAI null V00011 11/06/18,
ANDERS,SAND null V000103 07/10/17,
"",
PSP SECONDARY,
MUNCH,TORY null V000113 04/08/19 ,
"There is no key words here",
PCC WITH SOEMTHING,
BEC,RUMA null V00011 04/17/19 ,
"There is no keyword here too",
ASP HAS IT,
XON,ANDREA null V00011 03/27/19]

我有一个这样的关键词列表:

key_word_list = ['PCC', 'PSP', 'ASP']

现在,当我遍历 key_word_list 中的每个关键字时,如果找到关键字,则在找到关键字的那一行之后添加这些值记录,直到下一个关键字。像这样的输出,

["Started with no key words",
PCC WITH NOTHING,
PCC ABB,CAI null V00011 11/06/18,
PCC ANDERS,SAND null V000103 07/10/17,
"",
PSP SECONDARY,
PSP MUNCH,TORY null V000113 04/08/19 ,
"There is no key words here",
PCC WITH SOEMTHING,
PCC BEC,RUMA null V00011 04/17/19 ,
"There is no keyword here too",
ASP HAS IT,
ASP XON,ANDREA null V00011 03/27/19]

我如何在 python 中执行此操作?可行吗?最好的方法是什么?我从这样的事情开始,

for ind, j in enumerate(key_word_list):
# intermediate_index = [] # Was thinking to save index, but no idea what to do with this either to proceed to next line until next key word
for index,i in enumerate(biglist):
stripped_line = i.strip()
if j in stripped_line:
#do something not sure how to check until next keyword

最佳答案

您可以制作一个生成器函数,在它经过时跟踪当前关键字和 yield 行:

def append_keys(l, kw):
current_kw = None

for line in l:
# deal with initial lines with no kw
if current_kw is None and not any(line.startswith(k) for k in kw):
yield line
continue
try:
k = next(k for k in kw if line.startswith(k))
current_kw = k
yield line
except StopIteration:
yield current_kw + " " + line

new_list = list(append_keys(biglist, key_word_list))

新列表:

['PCC WITH NOTHING',
'PCC ABB,CAI null V00011 11/06/18',
'PCC ANDERS,SAND null V000103 07/10/17',
'PSP SECONDARY',
'PSP MUNCH,TORY null V000113 04/08/19',
'PCC WITH SOEMTHING',
'PCC BEC,RUMA null V00011 04/17/19',
'ASP HAS IT',
'ASP XON,ANDREA null V00011 03/27/19']

作为生成器意味着您可以一次循环一个列表,而无需在内存中创建另一个列表(如果您愿意的话)——如果列表真的很大,这很好。

关于python - 将关键字值添加到下一行,直到找到下一个关键字 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com