看看get_text(),我们似乎需要修改一些东西,然后才能删除任何标点符号。我在这里添加了一些评论。在def get_text():
str_lines = [] # create an empty list
url = 'http://www.gutenberg.org/files/1155/1155-h/1155-h.htm'
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'html.parser')
text = soup.find_all('p') #finds all of the text between
i=0
for p in text:
i+=1
line = p.get_text()
if (i<10):
continue
str_lines.append(line) # append the current line to the list
return str_lines # return the list of lines
首先,我取消了str_lines变量的注释,并将其设置为空列表。接下来,我用代码替换了print语句,将该行追加到行列表中。最后,我更改了return语句以返回该行列表。在
对于strip_text(),我们可以将其简化为几行代码:
^{pr2}$
不需要按单词进行操作,因为我们可以查看整行并删除所有标点,因此我删除了split()。使用list comprehension,我们可以在一行中更改列表的每个元素,并且我还将lower()方法放在其中以压缩代码。在
要实现@AhsanulHaque提供的答案,只需将strip_text()方法的第二行替换为它,如图所示:def strip_text():
list_words = get_text()
list_words = ["".join(j.lower() for j in i if j not in string.punctuation)
for i in list_words]
return list_words
有趣的是,我前面提到的为Python3.x实现的translate方法,如here所述:def strip_text():
list_words = get_text()
translator = str.maketrans({key: None for key in string.punctuation})
list_words = [s.lower().translate(translator) for s in list_words]
return list_words
不幸的是,我无法为您的特定代码计时,因为Gutenberg暂时阻止了我(我想代码运行太多太快了)。在