#Проблема с парсингом больших файлов
#Здравствуйте!
#Программа должна перемешивать определённые слова в заданном соотношении. Определенные слова в данном случае Components="Pb" и Components="Cd". Соотношение задается с помощью процентов
#Проблема в том, что в промежуточном файле вывода не все искомые строки. Отсюда, когда искомые слова вставляются на исходные места, файл вывода оказывается в несколько раз короче входного.
import random, re
with open("infile.txt",'r') as f:
lines = f.read()
component_1 = re.findall('([^\s].*?Components="Cd".*?)', lines) # что ищем
component_2 = re.findall('([^\s].*?Components="Pb".*?)', lines)
def count(com1, com2):
result = []
if com1 != 0:
l_1 = len(com1)
a = input('Cd ')
else:
l_1 = 0
if com2 != 0:
l_2 = len(com2)
b = input('Pb ')
else:
l_2 = 0
if round(l_1//100) < 1:
nominal_1_proc = round(l_1//100)+1
else:
nominal_1_proc = round(l_1//100)
if round(l_2//100) < 1:
nominal_2_proc = round(l_2//100)+1
else:
nominal_2_proc = round(l_2//100)
if com1 != 0:
for x in range(0, int(a*nominal_1_proc)):
result.append(com1[x])
if com2 != 0:
for y in range(0, int(b*nominal_2_proc)):
result.append(com2[y])
random.shuffle(result)
return result
fo = open("demooutfile.txt", "w")
for y in count(component_1, component_2):
fo.write(y)
fo.write('\n')
fo.close()
regex3= re.compile('Components="Pb"|Components="Cd"') # что ищем
with open("infile.txt",'r') as f3:
lines3 = f3.read()
endpos3=0
match3= regex3.search(lines3,endpos3)
matches3=[] # массив с совпадениями
strings3=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка
# поэтому значения в массивах чередуются относительно целевой строки
while (match3):
strings3+= [ lines3[endpos3:match3.start()] ]
endpos3= match3.end()
matches3+=[match3.group(0)]
match3= regex3.search(lines3,endpos3)
if (endpos3==len(lines3)): strings3+= [ "" ]
random.shuffle(matches3)
regex2= re.compile('Components="Pb"|Components="Cd"') # что ищем
with open("demooutfile.txt",'r') as f2:
lines2 = f2.read()
endpos2=0
match2= regex2.search(lines2,endpos2)
matches2=[] # массив с совпадениями
strings2=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка
# поэтому значения в массивах чередуются относительно целевой строки
while (match2):
strings2+= [ lines2[endpos2:match2.start()] ]
endpos2= match2.end()
matches2+=[match2.group(0)]
match2= regex2.search(lines2,endpos2)
if (endpos2==len(lines2)): strings2+= [ "" ]
random.shuffle(matches2)
result3= "" # собираем строку обратно с перемешанными данными
for i in range(len(matches2)):
result3+=strings3[i]+matches2[i] # вместо исходного массива вставляем искомый
result3+=strings3[-1]
with open("outfilenew.txt", "w") as f4:
f4.write(result3)