Python:从两个不同的文件中找到精确的句子

2024-05-11 03:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

你好。我是Python新手,正在寻找从文本文件中搜索另一个html文件上确切关键字(可能是长字符串)的代码。例如关键字.txt以及数据.html. 目前它只匹配第一个单词,而不是精确的句子匹配。你知道吗

我的关键字文件包含:

Hello welcome
Hello welcome to this page
Hello world

我的数据文件包含:

Hello
hello good day

对于这个条件,它应该返回:no match,但是当前它返回“match found”。你知道吗

以及如何确保它根据html页面逐行搜索所有关键字。你知道吗

非常感谢。提前谢谢。你知道吗

我的当前代码:

import re

keyfile = 'keyword.txt'
testfile = 'data.txt'
keys = set(key.lower() for key in
    re.findall(r'\w+', open(keyfile , "r").readline()))
with open(testfile) as f:
    for line in f:
        words = set(word.lower() for word in re.findall(r'\w+', line))
        if keys & words:
            print "match found"

Tags: 文件代码inretxthelloforhtml
1条回答
网友
1楼 · 发布于 2024-05-11 03:31:24

修改第6行。从re.findall(r'\w+', open(keyfile , "r").readline()))open(keyfile , "r"))将整行放入key集合,而不仅仅是单词。您还需要修改匹配零件以匹配线。你知道吗

因此,您的代码如下所示:

import re

keyfile = 'keyword.txt'
testfile = 'data.txt'
keys = set(key.lower() for key in
    open(keyfile , "r"))
with open(testfile) as f:
    for line in f:
        if line.lower() in keys:
            print "match found"

那应该能解决你的问题。你知道吗

相关问题 更多 >