我现在正在用Python做一个项目,我们应该从一个Gutenberg项目文件中解析HTML来隔离这本书的内容。我设法把所有东西都处理掉了,除了目录。我想通过使汤.美化()一个string对象,在目录的最后一个短语上拆分它,并从列表中拉出最后一个元素,它将是除目录之外的所有元素。这就是我目前所拥有的。你知道吗
def get_text(): #writes the html into a new text file called new_christie.txt
with open('new_christie.txt','w', encoding='utf-8') as book:
url = 'http://www.gutenberg.org/files/1155/1155-h/1155-h.htm'
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'html.parser')
str = soup.prettify()
text = str.split('XXVIII. AND AFTER') #last phrase in Table of Contents
text = soup.find_all('p') #finds all of the text between paragraphs
content = text[-1:]
for p in content:
line = p.get_text()
book.write(line)
我认为我的问题在于,当我试图使用content=text[-1:]从列表中拉出最后一个元素时,我想不出另外一种方法。你知道吗
我提供这个解决方案,除了注意我使用lxml而不是美丽的汤,因为我知道它更好。我不记得它是不是本机安装的,但是您可以在终端中用
pip install lxml
安装它。你知道吗相关问题 更多 >
编程相关推荐