在文件中搜索单词,但不作为另一个单词的一部分

时间:2017-08-29 05:22:16

标签: python

我有一个文本文件,每行一个单词。每个单词实际上可以是没有空格的几个单词组合,例如thisisthexample

现在,我有一个测试词,我检查文件:

if test_word in open(FILENAME).read():

如果test_word = "example"thisistheexample是文件中的一行,则上述语句将评估为True,是否正确?

有没有解决方法,如果文件中只有True,则只返回"example",而"example"加上一个或多个字符没有其他组合?我会在下面做这样的事吗?

with open(FILENAME) as file:
    for line in file:
        if line == test_word

谢谢!

3 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

base64_encode(sha1($sec-websocket-key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));

答案 1 :(得分:0)

您可以使用re模块和\ b来检查:

import re
a = 'If test_word = "example", and thisistheexample is one of the lines in the file, the statement above will evaluate to True, correct?'
regex = re.compile(r"\bexample\b")
result = regex.findall(a)

如果结果长度不为零,则该单词存在。

答案 2 :(得分:-1)

您可能想要使用readline方法

with open("file.txt") as _fp:
    _words = _fp.readlines()
    for i in xrange(len(_words)):
        _words[i]=_words[i].strip()
    if 'search_word' in _words:
        print "Found"

如果在一行中没有空格的多个单词组合将在list中编入索引,您可以使用in查找完全匹配,或regex

这是一个例子:

>>> a=["applearered","banana"]
>>> "apple" in a
False
>>> "banana" in a
True