Как получить полные строки с поиском RegEx в python, который захватывает только часть слова? - PullRequest
1 голос
/ 09 апреля 2020

Мое задание состоит в поиске в документе и получении слов, содержащих ch, cH, Ch, CH, sh, sH, Sh и SH. Какой самый эффективный способ получить слово целиком? сейчас, используя re.findall (), я получаю правильное количество слов и местоположения, но могу печатать только ch или sh, а не все слово, содержащее буквы. Вот мой код!

import re

#f = open("dreamMLK.txt",'r')

with open("dreamMLK.txt",'r') as fp:
    line = fp.readline()
    count = 1
    while line:
        x = re.findall("ch|sh",line)
        if(len(x) > 0):
            print(x)
            print(str(count) +": "+line)
        line = fp.readline()
        count += 1

, а вот вывод:

['sh']
3: Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves [Audience:] (Yeah) who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity. (Hmm)

['ch', 'sh', 'sh']
5: But one hundred years later (All right), the Negro still is not free. (My Lord, Yeah) One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. (Hmm) One hundred years later (All right), the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later (My Lord) [applause], the Negro is still languished in the corners of American society and finds himself in exile in his own land. (Yes, yes) And so we’ve come here today to dramatize a shameful condition.

Я хочу, чтобы в строке 3 печаталось значение Shadow, а не 'sh'. И строка 5, чтобы напечатать Цепи, Языки и Позор. Вот дословное присвоение, если интересно:

Откройте файл и, используя l oop для чтения в каждой строке, используйте регулярные выражения (re.search ()), чтобы найти те строки, которые содержат любую строчную или строчную версию строчек "ch" или sh ", т. е. {ch Ch cH CH sh sH Sh SH}. ПРИМЕЧАНИЕ. - не перечисляйте все 8 возможностей в регулярном выражении, скорее, ваше регулярное выражение должно быть длиной 7 символов, включая символы []. Для каждого предложения, содержащего "ch" или "sh" (или Ch или CH или cH et c), выведите: a) строку номер и отправка, а также b) список слов в этом предложении, содержащий некоторую версию "sh" или "ch".

1 Ответ

0 голосов
/ 09 апреля 2020

Попробуйте использовать следующий шаблон регулярных выражений в нечувствительном к регистру режиме:

\b\S*[cs]h\S*\b

Это будет соответствовать всем словам, содержащим ch или sh. Вот пример сценария:

# -*- coding: utf-8 -*-
inp = """3: Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves [Audience:] (Yeah) who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.
5: But one hundred years later (All right), the Negro still is not free. (My Lord, Yeah) One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. (Hmm) One hundred years later (All right), the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later (My Lord) [applause], the Negro is still languished in the corners of American society and finds himself in exile in his own land. (Yes, yes) And so we’ve come here today to dramatize a shameful condition."""

matches = re.findall(r'\b\S*[cs]h\S*\b', inp, flags=re.IGNORECASE)
print(matches)

Это печатает:

['shadow', 'chains', 'languished', 'shameful']
...