python - 使用 Python 检查 HTML 文本中的多个字符串(来自文件)

标签 python arrays string find scrapy

我需要在 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/

相关文章:

python - 同时 MySQLdb 连接看不到更新

c - 如何将文件的内容存储到数组中(C)

C:启动并命名字符串数组

java - StringBuffer 未完全读取

c# - Microsoft C# 字符串文档 : Am I misinterpreting what I read, 还是文档有误?

python - 尝试使用正则表达式提取字符串 - Python

python - 如何在 Pandas 数据框中将其分开?

c++ - 多维数组逻辑

python - Python 2 和 3 中的字符串到字节

python - 如何将 Spark Streaming 与 TensorFlow 集成?