import urllib.request
url = 'http://www.gutenberg.org/cache/epub/1342/pg1342.txt'
book = urllib.request.urlopen(url)
lines = book.readlines()
book.close()
import re
title_regex = re.compile(b'\*{3} START OF THIS PROJECT GUTENBERG EBOOK (.*?) \*{3}')
for index, line in enumerate(lines):
match = title_regex.match(line)
if match:
book_name = match.group(1)
print(book_name)
import re
title_regex = re.compile(r'\*{3} START OF THIS PROJECT GUTENBERG EBOOK (.*?) \*{3}')
for index, line in enumerate(finalLines):
match = title_regex.match(line)
if match:
book_name = match.group(1)
print(index, book_name)
Regex是一条出路:
也可以逐行解析:
^{pr2}$最简单的解决方案:
一个更好的解决方案将使用正则表达式,正如建议的那样。在
如果使用字节,则应使用
b'*** START OF THIS PROJECT GUTENBERG EBOOK ***'
,或对任何字节字符串使用bytes.decode(s)
。在您的代码段(带有
^{pr2}$urlopen()
部分)可能如下所示:相关问题 更多 >
编程相关推荐