fork download
  1. #Проблема с парсингом больших файлов
  2. #Здравствуйте!
  3. #Программа должна перемешивать определённые слова в заданном соотношении. Определенные слова в данном случае Components="Pb" и Components="Cd". Соотношение задается с помощью процентов
  4. #Проблема в том, что в промежуточном файле вывода не все искомые строки. Отсюда, когда искомые слова вставляются на исходные места, файл вывода оказывается в несколько раз короче входного.
  5. import random, re
  6.  
  7. with open("infile.txt",'r') as f:
  8. lines = f.read()
  9.  
  10. component_1 = re.findall('([^\s].*?Components="Cd".*?)', lines) # что ищем
  11. component_2 = re.findall('([^\s].*?Components="Pb".*?)', lines)
  12.  
  13. def count(com1, com2):
  14. result = []
  15. if com1 != 0:
  16. l_1 = len(com1)
  17. a = input('Cd ')
  18. else:
  19. l_1 = 0
  20. if com2 != 0:
  21. l_2 = len(com2)
  22. b = input('Pb ')
  23. else:
  24. l_2 = 0
  25. if round(l_1//100) < 1:
  26. nominal_1_proc = round(l_1//100)+1
  27. else:
  28. nominal_1_proc = round(l_1//100)
  29. if round(l_2//100) < 1:
  30. nominal_2_proc = round(l_2//100)+1
  31. else:
  32. nominal_2_proc = round(l_2//100)
  33. if com1 != 0:
  34. for x in range(0, int(a*nominal_1_proc)):
  35. result.append(com1[x])
  36. if com2 != 0:
  37. for y in range(0, int(b*nominal_2_proc)):
  38. result.append(com2[y])
  39. random.shuffle(result)
  40. return result
  41.  
  42. fo = open("demooutfile.txt", "w")
  43. for y in count(component_1, component_2):
  44. fo.write(y)
  45. fo.write('\n')
  46. fo.close()
  47.  
  48. regex3= re.compile('Components="Pb"|Components="Cd"') # что ищем
  49. with open("infile.txt",'r') as f3:
  50. lines3 = f3.read()
  51. endpos3=0
  52. match3= regex3.search(lines3,endpos3)
  53. matches3=[] # массив с совпадениями
  54. strings3=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка
  55. # поэтому значения в массивах чередуются относительно целевой строки
  56. while (match3):
  57. strings3+= [ lines3[endpos3:match3.start()] ]
  58. endpos3= match3.end()
  59. matches3+=[match3.group(0)]
  60. match3= regex3.search(lines3,endpos3)
  61. if (endpos3==len(lines3)): strings3+= [ "" ]
  62. random.shuffle(matches3)
  63.  
  64. regex2= re.compile('Components="Pb"|Components="Cd"') # что ищем
  65. with open("demooutfile.txt",'r') as f2:
  66. lines2 = f2.read()
  67. endpos2=0
  68. match2= regex2.search(lines2,endpos2)
  69. matches2=[] # массив с совпадениями
  70. strings2=[] # все остальное что не совпало, при этом если два совпадения подряд, или начало (конец) строки и совпадение, то в этот массив попадает пустая строка
  71. # поэтому значения в массивах чередуются относительно целевой строки
  72. while (match2):
  73. strings2+= [ lines2[endpos2:match2.start()] ]
  74. endpos2= match2.end()
  75. matches2+=[match2.group(0)]
  76. match2= regex2.search(lines2,endpos2)
  77. if (endpos2==len(lines2)): strings2+= [ "" ]
  78. random.shuffle(matches2)
  79.  
  80. result3= "" # собираем строку обратно с перемешанными данными
  81. for i in range(len(matches2)):
  82. result3+=strings3[i]+matches2[i] # вместо исходного массива вставляем искомый
  83. result3+=strings3[-1]
  84.  
  85. with open("outfilenew.txt", "w") as f4:
  86. f4.write(result3)
  87.  
Runtime error #stdin #stdout #stderr 0.02s 10328KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "prog.py", line 7, in <module>
IOError: [Errno 2] No such file or directory: 'infile.txt'