2014-12-17 2 views
0

두 개의 문서가 있습니다. 하나는 XML이다 :루프의 루프가 모든 결과를 표시하지 않습니다.

<sdl> 
<group> 
    <trans-unit id="57628711-51bd-4e2c-811c-7fa7a5a1cac0"> 
     <source><g id="67">G_Source_1</g>Source_1</source> 
     <seg-source><mrk mtype="seg" mid="4">Seg_Source_1</mrk></seg-source> 
     <target><mrk mtype="seg" mid="4"><g id="67">G_Target_1</g>Target_1</mrk></target> 
    </trans-unit> 
</group> 
<group> 
     <trans-unit id="7da4f54e-1fa9-46b3-846e-e7745840dcd8"> 
      <source><g id="970">G_Source_6.1</g>Source_6<g id="971">G_Source_6.2</g></source> 
      <seg-source><mrk mtype="seg" mid="921">Seg_Source_6</mrk></seg-source> 
      <target><mrk mtype="seg" mid="921"><g id="970">G_Target_6.1</g>Target_6<g id="971">G_Target_6.2</g></mrk></target> 
     </trans-unit> 
</group> 
</sdl> 

그리고 또 다른 탭은 .txt 파일을 분리합니다.

G_Source_1 G_Target_1 
G_Source_6.1 G_Target_6.1 
G_Source_6.1 G_Target_6.2 

이 코드는 TXT 파일의 첫째 열에서 모든 텍스트와 XML 파일에서 <g> 태그의 모든 텍스트를 comapre한다. 그리고이 모든 결과를 나타냅니다.

glo = File.open(glo_file) 
sdlxlff = Nokogiri::XML(open(sdlxlff_file)) 
sdlxlff.remove_namespaces! 
sdlxlff_content = sdlxlff.xpath("//trans-unit") 
sdlxlff_content.each do |product| 
    source_sdl = product.xpath("source/g").text 
    target_sdl = product.xpath("target//g").text 
    mid = product.xpath("target//mrk/@mid") 
    glo.each_line do |line| 
    content_glo = line.split("\t",2) 
    source_glo = content_glo[0] 
    target_glo = content_glo[1] 
    if source_sdl == source_glo 
     puts "same" 
     puts source_glo 
     puts source_sdl 
     puts mid 
    end 
    end 
end 

을하지만 XML의 첫번째 문자열에 대한 결과가있다 :

나는이 코드를 다음 한

same 
G_Source_1 
G_Source_1 
4 

당신이 내 문제를 가리 시겠어요. 이제 내 코드는 첫 번째 <g> 태그 만 비교하고 나머지는 건너 뜁니다.

sdlxlff_content.xpath('//trans-unit/target//g').text 
# => "G_Target_1G_Target_6.1G_Target_6.2" 

이러한 문제가 발생하지 않도록하려면 각에 text를 호출해야합니다

답변

1

귀하의 문제는 함께 모든 결과를 CONCAT 것입니다 거기에 text를 호출하여 xpath 일치하는 두 개 이상의 노드가있는 경우이다 요소의 일치 :

012 :

sdlxlff_content.xpath('//trans-unit/target//g').map { |x| x.text } 
# => ["G_Target_1", "G_Target_6.1", "G_Target_6.2"] 

그래서 당신이 뭔가를 찾기 위해 코드를 변경할 수 있습니다 3,516,

sdlxlff_content.each do |product| 
    source_sdl = product.xpath("source/g").map { |x| x.text } 
    target_sdl = product.xpath("target//g").map { |x| x.text } 
    mid = product.xpath("target//mrk/@mid") 
    glo.each_line do |line| 
    content_glo = line.split("\t",2) 
    source_glo = content_glo[0] 
    target_glo = content_glo[1] 
    if source_sdl.any? { |x| x == source_glo } 
     puts "same" 
     puts source_glo 
     puts "#{source_sdl}" 
     puts mid 
    end 
    end 
end 

출력 :

same 
G_Source_1 
["G_Source_1"] 
4 
same 
G_Source_6.1 
["G_Source_6.1", "G_Source_6.2"] 
921 
same 
G_Source_6.1 
["G_Source_6.1", "G_Source_6.2"] 
921 
0

고마워요. 그러나 나는 문제를 발견했다. 두 번째 루프가 1 차 실행 된 후 파일을 닫지 않았습니다. glo.close를 추가 한 후 첫 번째 루프가 끝납니다. 모두가 exoected로 작동하게됩니다.

감사합니다. 스타 니 슬라브