我需要在 Python 中根据文本文件中的多个字符串检查废弃的 HTML 文档。换句话说,蜘蛛应该找出 html 文本是否包含任何给定的字符串。
url = 'http://forum.unisoftdev.com'
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read()
with open('keywords.txt') as f:
key_words = f.readlines()
# here's the nut:
if key_words in html :
# do something
我不需要任何“elif”和“else”,因为我需要在文本文件中使用它,所以我必须根据多个字符串检查文档,但不知道如何在 Python 中执行此操作。在 PHP 中,这确实更容易......
最佳答案
您可以使用带有交替的正则表达式来检查输入文本中是否存在任何关键字。只需用alternations加入关键字即可一起。
pattern = "|".join(r'{}'.format(word) for word in key_words)
如果您不想要子字符串匹配,例如将 omegaforce 与 omega 匹配,然后您需要添加 word boundaries :
pattern = "|".join(r'\b{}\b'.format(word) for word in key_words)
示例代码:
import re
html = 'I have lots of deltas but no omegas'
key_words = ['alpha', 'omega','delta']
pattern = "|".join(r'{}'.format(word) for word in key_words)
rx = re.compile(pattern)
if rx.search(html):
# do something
print "found"
关于python - 使用 Python 检查 HTML 文本中的多个字符串(来自文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870524/