简体   繁体   English

使用 python 从数组中的字符串中删除特定行

[英]deleting a specific line from a string in an array with python

im have an array of strings where every position has a full paragraph as string.我有一个字符串数组,其中每个 position 都有一个完整的段落作为字符串。

im trying to delete a line from every paragraph in that string if they pass the condition如果他们通过条件,我试图从该字符串的每个段落中删除一行

for example:例如:

arr[0]= "A -agent: this line will be deleted arr[0]= "A -agent: 此行将被删除

client: this will remain the same客户:这将保持不变

A -agent: this will be deleted " A -agent:这将被删除“

im using this code to delete the whole line where the agent speaks but is not working我使用此代码删除代理说话但不工作的整行

def findAgentName(text):
    words= text.lower().split()
    agentName=[item for item in words if item[-6:] == '-agent']
    if agentName != None:
        agentName=agentName[:len(agentName)-6]
        return "\n".join([x.strip() for x in text.splitlines() if agentName not in x])
    else:
        return 

u can have a try like this:你可以试试这样:

arr = """A -agent : this line will be deleted
client: this will remain the same
A -agent: this will be deleted """

print(arr)
# A -agent : this line will be deleted
# client: this will remain the same
# A -agent: this will be deleted 

import re

agentName = "-agent"

regex = re.compile(rf".*{agentName}.*(\n)?")
new_arr = regex.sub('', arr)
print(new_arr)
# client: this will remain the same

Hi you can also try in this way:您好,您也可以这样尝试:

string = """A -agent : this line will be deleted
client: this will remain the same
A -agent: this will be deleted"""

list_string = string.lower().split("\n")
string_to_return = "\n".join(filter(lambda x: not "-agent" in x,list_string))

print(string_to_return)
#client: this will remain the same
def f(text):
    return '\n'.join([t for t in text.lower().splitlines() if not '-agent' in t])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM