Как преобразовать коллекцию XML поиска по социальным книгам в коллекцию TREC? - PullRequest
0 голосов
/ 18 мая 2019

Я использую платформу Terrier IR для своих экспериментов с набором данных Social Book Search, содержащим 2,8 миллиона документов XML, каждый из которых содержит более 67 полей метаданных. Пример XML-файла приведен ниже:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- version 1.0 / 2009-11-06T15:56:12+01:00 -->
<!DOCTYPE book SYSTEM "books.dtd">
<book>
<isbn>0373078005</isbn>
<title>Never Trust A Lady (Silhouette Intimate Moments, No 800) (Harlequin Intimate Moments, No 800)</title>
<ean>9780373078004</ean>
<binding>Paperback</binding>
<label>Silhouette</label>
<browseNode id="388186011">Refinements</browseNode>
<browseNode id="394174011">Binding (binding)</browseNode>
<browseNode id="400272011">Paperback</browseNode>
</browseNodes>
</book>

Однако перед индексацией я хочу преобразовать коллекцию в формат коллекции TREC. Все файлы XML в определенной папке должны быть преобразованы в один файл TREC, образец показан ниже:

<book>
<isbn>0373078005</isbn>
<text>0373078005 Never Trust A Lady (Silhouette Intimate Moments, No 800 (Harlequin Intimate Moments, No 800) 9780373078004 Paperback Silhouette $3.99 Silhouette Silhouette 1997-07-01 Silhouette Refinements Binding (binding) Paperback </text>
</book>
<book>
<isbn>0373084005</isbn>
<text>0373084005 Written On The Wind (Silhouette Romance, No 400) 9780373084005 Paperback Silhouette $1.95 Silhouette Silhouette 1985-11-01 Silhouette 70 420 650 10 Rita Rainville Author Artificial intellingence Romance contemporary sr category Romance Subjects Contemporary Series Silhouette Romance Books General Refinements Binding (binding) Paperback Format (feature_browse-bin) Printed Books General AAS</text>
</book>
...

Я создал C:\xmlfiles\python-trec и создал в нем две папки, а именно data1 и data2, и поместил несколько файлов xml в обе папки. Я использовал скрипт Python, доступный по адресу: http: lab.hypotheses.org/1129, который я изменил следующим образом:

import os, sys
from bs4 import BeautifulSoup
datadest="no collection path"
datdir = "C:\\xmlfiles\\python-trec\\"
for folds in os.listdir(datdir):
    os.mkdir(datadest+folds)
    trectxt=""
    for files in os.listdir(datdir+folds):
        if files.endswith(".xml"):
            content= open(datdir+"/"+folds+"/"+files,'r').read()
            soup = BeautifulSoup(content)
            texts = soup.findAll("book")
            for text in texts:
                isbn =texts[0].findAll("isbn")[0].getText()
                trectxt+="<book>\n<isbn>"+isbn+"</isbn>\n"
                trectxt+="<text>"+' '.join(texts[0].findAll(text=True))+"</text>\n</book>\n"
                f=open(datadest+folds+"/"+folds+".xml","w")
                f.write(trectxt)
                f.close()

Я получаю следующее сообщение об ошибке:

C:\Python27>python C:\Python27\Scripts\trec-conversion.py
Traceback (most recent call last):
  File "C:\Python27\Scripts\trec-conversion.py", line 6, in <module>
   os.mkdir(datadest+folds)
 WindowsError: [Error 183] Cannot create a file when that file already exists: 'no collection pathdata1'

После изменения строки: datadest="no collection path" на datadest="C:\\xmlfiles\\python-trec\\" я получил следующее сообщение об ошибке:

C:\Python27>python C:\Python27\Scripts\trec-conversion.py
Traceback (most recent call last):
  File "C:\Python27\Scripts\trec-conversion.py", line 6, in <module>
   os.mkdir(datadest+folds)
WindowsError: [Error 183] Cannot create a file when that file already exists: 'C:\\xmlfiles\\python-trec\\data1'

Затем я создал новую папку C:\\xmlfiles\\python-trec\\python-trec-results и изменил строку: datadest="no collection path" на datadest="C:\\xmlfiles\\python-trec\\python-trec-results", я получил следующее сообщение об ошибке:

C:\Python27\Scripts\trec-conversion.py:11: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 11 of the file 
C:\Python27\Scripts\trec-conversion.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor.

soup = BeautifulSoup(content)
Traceback (most recent call last):
File "C:\Python27\Scripts\trec-conversion.py", line 18, in <module>
    f.write(trectxt)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 1141: ordinal not in range(128)

Код генерирует требуемый файл TREC для папки data1, но не может создать то же самое для папки data2 с указанным выше сообщением.

Пожалуйста, помогите

- Rocky

1 Ответ

0 голосов
/ 18 мая 2019

Я внес следующие изменения:

# encoding=utf8
import os, sys
reload(sys)
sys.setdefaultencoding('utf8')

from bs4 import BeautifulSoup

datadest="C:\\xmlfiles\\python-trec-results\\"
datdir = "C:\\xmlfiles\\python-trec\\"

for folds in os.listdir(datdir):
    os.mkdir(datadest+folds)
    trectxt=""
    for files in os.listdir(datdir+folds):
        if files.endswith(".xml"):
            content= open(datdir+"/"+folds+"/"+files,'r').read()
            soup = BeautifulSoup(content, 'lxml', from_encoding='utf-8')
            texts = soup.findAll("book")
            for text in texts:
                isbn =texts[0].findAll("isbn")[0].getText()
                trectxt+="<book>\n<isbn>"+isbn+"</isbn>\n"
                trectxt+="<text>"+' '.join(texts[0].findAll(text=True))+"</text>\n</book>\n"
                f=open(datadest+folds+"/"+folds+".xml","w")
                f.write(trectxt)
                f.close()

и программа работает сейчас! Однако это дает слишком много лишних пробелов внутри значения узлов и, как видно ниже:

<book>
<isbn>0268020000</isbn>
<text>
0268020000 
Aquinas On Matter and Form and the Elements: A Translation and Interpretation of the DE PRINCIPIIS NATURAE and the DE MIXTIONE ELEMENTORUM of St. Thomas Aquinas 
9780268020002 
Paperback 
University of Notre Dame Press 
$25.00 
University of Notre Dame Press 
University of Notre Dame Press 


1998-03-28 
University of Notre Dame Press 

2000-11-16 
Wonderful Exposition 
Bobick has done it again.  After reading Bobick's insightful translation and exposition of Aquinas' "De Ente et Esentia", I was pleased to find that his knack for explaining Aquinas' complex ideas in metaphysics and natural philospohy is repeated in this book.  For those who wish to understand Aquinas in depth, this book is a must. 
5 
0 
0 

Physics 
Cosmology 
Professional & Technical 



</text>
</book>
<book>
<isbn>0268037000</isbn>
<text>
0268037000
... 

Я хочу удалить ненужные пробелы и вернуть, чтобы это выглядело следующим образом:

<book>
<isbn>0268020000</isbn>
<text> ....text goes here....</text>
</book>
<book>
<isbn> 0268037000 </isbn>
<text>....text goes here.....</text>
</book>
...

Я пробовал доступные ответы на удаление пробелов, но они не работают для меня ... Пожалуйста, помогите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...