第一次在这里张贴问题,我通常通过搜索找到了答案,但这个时候,我来到了干。
我用Python写一个非常简单的功能,但它拒绝返回一个值。基本上你应该输入HTML代码,它会删除所有的HTML标签(通过搜索<和>,然后拼接一个新的字符串)。
def pretty_print(source_code):
article_nohtml = remove_html(source_code)
print(article_nohtml)
def remove_html(article):
code_starts_at = article.find('<')
if code_starts_at != -1:
beginning_of_article = article[:code_starts_at]
code_ends_at = article.find('>')+1
end_of_article = article[code_ends_at:]
stitched_article = beginning_of_article + end_of_article
remove_html(stitched_article)
else:
print(type(article))
print(article)
return article
#Test the function
remove_html('<p>This is a text to <strong> try the script out </strong></p>\n<p>Is this working for you?</p>')
这段代码不包含任何非凡的东西,所以它是一个谜,为什么它不工作。我添加了最后两个打印调用来测试函数,它们返回类'str'和完整的字符串,看起来不错,但是当pretty_print函数应该打印文章时,它只输出None。
感谢所有帮助我能,这应该是简单的,但我可能失去了一些东西。
'remove_html'只会在执行'else'分支时返回一个值。 – snakecharmerb
你不会在'if'条件的第一部分返回任何东西。为什么不使用库(例如beautifulsoup)进行html解析? –
@snakecharmerb确实如此,但当所有的代码都被删除后,else语句就会被执行。 –