Python поиск точной строки в файле - PullRequest
0 голосов
/ 17 июня 2020
import re

def find_string(file_name, word):
   with open(file_name, 'r') as a:
       for line in a:
           line = line.rstrip()
           if re.search("^{}$".format(word),line):
             return True
   return False

if find_string('/tmp/myfile', 'hello'):
    print("found")
else:
    print("not found")

myfile:

hello world #does not match
hello #match

Если я удалю ^ и $, он будет соответствовать, но он также будет соответствовать «he», «hel» et c. Как я могу сопоставить точную строку, если в одной строке несколько слов?

Ответы [ 2 ]

1 голос
/ 18 июня 2020

Вы можете попробовать использовать границы слов вокруг текста. Что-то вроде:

\bhello\b

Вы можете найти демонстрацию вышеуказанного регулярного выражения в здесь.

Пример реализации в Python

import re
def find_string(file_name, word):
   with open(file_name, 'r') as a:
       for line in a:
           line = line.rstrip()
           if re.search(r"\b{}\b".format(word),line):
             return True
   return False

if find_string('myfile.txt', 'hello'):
    print("found")
else:
    print("not found")

Вы можете найти пример выполнения вышеуказанной реализации в здесь.

0 голосов
/ 17 июня 2020

Вы хотите что-то подобное? Извините, если нет

import re

with open('regex.txt', 'r') as a:
    word = "hello"
    for line in a:
        line = line.rstrip()
        if re.search(r"({})".format(word), line):
            print(f'{line} ->>>> match!')
        else:
            print(f'{line} ->>>> not match!')
text file:
hello world #does not match
hello #match
test here
teste hello here

[output]
hello world #does not match ->>>> match!
hello #match ->>>> match!
test here ->>>> not match!
teste hello here ->>>> match!
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...