连接后面的子字符串的一部分,并删除这些子字符串

2024-09-22 16:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我有一个文本文件,需要在其中连接()中的字符串并在concat之后删除。你知道吗

你知道吗文本.txt你知道吗

Car(skoda,benz,bmw,audi)
The above mentioned cars are sedan type and gives long rides efficient
......

Car(Rangerover,Hummer)
SUV cars are used for family time and spacious.

期望输出

Car(skoda,benz,bmw,audi,Rangerover,Hummer)
The above mentioned cars are sedan type and gives long rides efficient
......
SUV cars are used for family time and spacious.

这里的车应该添加到括号内的第一辆车,然后删除我连接的行。你知道吗

编码:

f_in=open("text.txt", "r")      
in_lines=f_in.readlines()           
out=[]
for line in in_lines:
    list_values=line.split()       
    for 'Car' in line:
        Car[i]=eval(list_values[i])    
        if Car[i] in line:     
            str(Car+Car[i]) #i m stuck and my overall logic is getting worse'

请帮我弄到想要的东西输出.due由于缺乏经验,我不知道最简单的方法这个。答案将不胜感激。你知道吗


Tags: andtheintxtforlinecarcars
2条回答

棘手的替换

搜索:

(?s)^(Car\([^),]+(,)[^)]*)(?=.*?Car\(([^)]+)\))|(?!^)Car\([^)]*\)[\r\n]*

替换:

\1\2\3

the Regex Demo中,请参见底部的替换。你知道吗

如果有两个以上的Car定义,则运行此替换,直到结果字符串与原始字符串相同。你知道吗

Python代码示例

subject=""
result= // paste your original string
while result != subject:
    subject = result
    result = re.sub(r"(?s)^(Car\([^),]+(,)[^)]*)(?=.*?Car\(([^)]+)\))|(?!^)Car\([^)]*\)[\r\n]*",
                    r"\1\2\3",
                    subject)

您可以使用re查找所有汽车,然后写下不包括带汽车的行:

import re
comp = re.compile('([^\(]*)\)')
with open("in.txt") as f, open("amended.txt","w") as f1:
    lines = f.read() # read line into one string
    cars = re.findall(comp,lines) # find all cars
    joined = " ".join([" ".join(x.split(",")) for x in cars]) # join all cars inside one set of parens
    f1.write("Car({})\n".format(joined)) # write cars to first line
    f.seek(0) # go back to start
    for line in f:
        if "Car(" not in line: # ignore lines with Car(....
            f1.write("{}".format(line))

它输出:

Car(skoda benz bmw audi Rangerover Hummer)
The above mentioned cars are sedan type and gives long rides efficient
SUV cars are used for family time and spacious.

相关问题 更多 >