Я пытаюсь очистить страницы с помощью паука Scrapy, а затем сохранить эти страницы в файл .txt в читаемой форме. Код, я использую, чтобы сделать это:Форматирование вывода текста с помощью Scrapy в Python
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
hxs = HtmlXPathSelector(response)
title = hxs.select('/html/head/title/text()').extract()
content = hxs.select('//*[@id="content"]').extract()
texts = "%s\n\n%s" % (title, content)
soup = BeautifulSoup(''.join(texts))
strip = ''.join(BeautifulSoup(pretty).findAll(text=True))
filename = ("/Users/username/path/output/Hansard-" + '%s'".txt") % (title)
filly = open(filename, "w")
filly.write(strip)
Я объединил BeautifulSoup здесь, потому что текст тела содержит много HTML, что я не хочу в конечном продукте (в первую очередь, ссылки), так что я используйте BS, чтобы вычеркнуть HTML и оставить только текст, который представляет интерес.
Это дает мне выход, который выглядит как
[u"School, Chandler's Ford (Hansard, 30 November 1961)"]
[u'
\n \n
HC Deb 30 November 1961 vol 650 cc608-9
\n
608
\n
\n
\n
\n
\xa7
\n
28.
\n
Dr. King
\n
\n asked the Minister of Education what is the price at which the Hampshire education authority is acquiring the site for the erection of Oakmount Secondary School, Chandler\'s Ford; and why he refused permission to acquire this site in 1954.\n
\n
\n
\n \n
\n
\n
\n
\xa7
\n
Sir D. Eccles
\n
\n I understand that the authority has paid \xa375,000 for this site.\n \n
В то время как я хочу, выход выглядеть следующим образом:
School, Chandler's Ford (Hansard, 30 November 1961)
HC Deb 30 November 1961 vol 650 cc608-9
608
28.
Dr. King asked the Minister of Education what is the price at which the Hampshire education authority is acquiring the site for the erection of Oakmount Secondary School, Chandler's Ford; and why he refused permission to acquire this site in 1954.
Sir D. Eccles I understand that the authority has paid £375,000 for this site.
Так что я в основном ищет, как удалить новой строки индикаторы \n
, затянуть все, и конвертировать любые специальные символы в их нормальный формат.
Спасибо за ваш комментарий. Однако, когда я его запускаю, я получаю сообщение об ошибке: \t 'cleaned_content = re.sub (ur '(\ s) \ s +', ur '\ 1', content, flags = re.MULTILINE + re.UNICODE) \t exceptions.TypeError: sub() получил неожиданный аргумент ключевого слова 'flags''. Есть предположения? – user1074057
@ user1074057 вы используете python <2.7 или <3.1, в этом случае вам нужно скомпилировать выражение: 'strip_re = re.compile (ur '(\ s) \ s +', re.MULTILINE + re.UNICODE); cleaned_content = strip_re.sub (ur '\ 1', content) ' – reclosedev
Это работает отлично. Принимается и поддерживается. Спасибо за вашу помощь! – user1074057