У меня есть пример текста такого письма. Я хочу сохранить только основную часть текста и удалить из текста имена, адреса, обозначения, названия компаний, адреса электронной почты. Итак, чтобы быть ясным, я хочу только содержание каждого письма между «Уважаемый/Привет/Привет» и «С уважением/С уважением/Спасибо». Как сделать это эффективно, используя регулярное выражение или каким-либо другим способом
Subject: [EXTERNAL] RE: QUERY regarding supplement 73
Hi Roger,
Yes, an extension until June 22, 2018 is acceptable.
Regards,
Loren
Subject: [EXTERNAL] RE: QUERY regarding supplement 73
Dear Loren,
We had initial discussion with the ABC team us know if you would be able to extend the response due date to June 22, 2018.
Best Regards,
Mr. Roger
Global Director
[email protected]
78 Ford st.
Subject: [EXTERNAL] RE: QUERY regarding supplement 73
responding by June 15, 2018.check email for updates
Hello,
John Doe
Senior Director
[email protected]
Subject: [EXTERNAL] RE: QUERY regarding supplement 73
Please refer to your January 12, 2018 data containing labeling supplements to add text regarding this
symptom. We are currently reviewing your supplements and have
made additional edits to your label.
Feel free to contact me with any questions.
Warm Regards,
Mr. Roger
Global Director
[email protected]
78 Ford st.
Center for Research
Office of New Discoveries
Food and Drug Administration
[email protected]
Из этого текста я хочу только ВЫВОД:
Subject: [EXTERNAL] RE: QUERY regarding supplement 73
Yes, an extension until June 22, 2018 is acceptable.
We had initial discussion with the ABC team us know if you would be able to extend the response due date to June 22, 2018.
responding by June 15, 2018.check email for updates
Please refer to your January 12, 2018 data containing labeling supplements to add text regarding this
symptom. We are currently reviewing your supplements and have
made additional edits to your label.
Feel free to contact me with any questions.
Я проверю человека. Спасибо за ответ. Я проверю и дам вам знать
Мне все еще любопытно, работает ли этот ответ для вас или нет.
На самом деле это не работает, потому что это зависит от файла. Я написал несколько регулярных выражений, где, если строка начинается с ключевого слова, ее нужно игнорировать. Это очень похоже на это
Спасибо за отзыв. Практически невозможно разработать решение проблемы, используя только один пример, взятый из большого набора данных, содержащего элементы, которые не соответствуют параметрам выборки. Мой ответ был разработан для образца, а не для всего набора данных, как я и сказал.
Спасибо, я отметил это как полезное






Ниже приведен ответ, который работает для вашего текущего ввода. Код буду иметь необходимо скорректировать при обработке примеров, выходящих за рамки параметров, указанных в приведенном ниже коде.
with open('email_input.txt') as input:
# List to store the cleaned lines
clean_lines = []
# Reads until EOF
lines = input.readlines()
# Remove some of the extra lines
no_new_lines = [i.strip() for i in lines]
# Convert the input to all lowercase
lowercase_lines = [i.lower() for i in no_new_lines]
# Boolean state variable to keep track of whether we want to be printing lines or not
lines_to_keep = False
for line in lowercase_lines:
# Look for lines that start with a subject line
if line.startswith('subject: [external]'):
# set lines_to_keep true and start capturing lines
lines_to_keep = True
# Look for lines that start with a salutation
elif line.startswith("regards,") or line.startswith("warm regards,") \
or line.startswith("best regards,") or line.startswith("hello,"):
# set lines_to_keep false and stop capturing lines
lines_to_keep = False
if lines_to_keep:
# regex to catch greeting lines
greeting_component = re.compile(r'(dear.*,|(hi.*,))', re.IGNORECASE)
remove_greeting = re.match(greeting_component, line)
if not remove_greeting:
if line not in clean_lines:
clean_lines.append(line)
for item in clean_lines:
print (item)
# output
subject: [external] re: query regarding supplement 73
yes, an extension until june 22, 2018 is acceptable.
we had initial discussion with the abc team us know if you would be able to
extend the response due date to june 22, 2018.
responding by june 15, 2018.check email for updates
please refer to your january 12, 2018 data containing labeling supplements
to add text regarding this symptom. we are currently reviewing your
supplements and have made additional edits to your label.
feel free to contact me with any questions.
помог ли мой ответ ниже решить проблему, изложенную в вашем вопросе?