Обновление текстового файла из словаря Python - PullRequest
1 голос
/ 04 июня 2019

Привет, участники сообщества,

Предположим, у меня есть словарь на python:

dict = {'fresh air', 'entertainment system', 'ice cream', 'milk', 'dog', 'blood pressure'}

и список текстов, таких как:

text_file = ['is vitamin d in milk enough', 'try to improve quality level by automatic intake of fresh air', 'turn on the tv or entertainment system based on that individual preferences', 'blood pressure monitor', 'I buy more ice cream', 'proper method to add frozen wild blueberries in ice cream']

Я хочу отображать каждое вхождение фразы, принадлежащей словарю (скажем, на свежем воздухе), как #fresh_air# во всех вхождениях текстового файла, тогда как для каждого отдельного слова словаря (скажем, milk) вывод должен отображаться как #milk#, то есть добавление специальных символов в начале и конце во всех вхождениях текстового файла.

Вывод, который я хочу, должен быть в следующей форме (списки списков):

[[is vitamin d in #milk# enough], [try to improve quality level by automatic intake of #fresh_air#], [turn on the tv or #entertainment_system# based on the individual preferences], [#blood_pressure# monitor], [I buy more #ice_cream#], [proper method to add frozen wild blueberries in #ice_cream# with #milk#]]

Существует ли какой-либо стандартный способ добиться этого с минимальными затратами времени?

Я новичок в списках и обработке текста с использованием Python, я пытался использовать списки, но не смог достичь желаемых результатов. Любая помощь очень ценится.

1 Ответ

3 голосов
/ 04 июня 2019

Использование Regex.

Пример:

import re
data = {'fresh air', 'entertainment system', 'ice cream', 'milk', 'dog', 'blood pressure'}
pattern = re.compile("("+"|".join(data)+")")
text_file = ['is vitamin d in milk enough', 'try to improve quality level by automatic intake of fresh air', 'turn on the tv or entertainment system based on that individual preferences', 'blood pressure monitor', 'I buy more ice cream', 'proper method to add frozen wild blueberries in ice cream']

result = [pattern.sub(r"#\1#", i) for i in text_file]
print(result)

Выход:

['is vitamin d in #milk# enough',
 'try to improve quality level by automatic intake of #fresh air#',
 'turn on the tv or #entertainment system# based on that individual preferences',
 '#blood pressure# monitor',
 'I buy more #ice cream#',
 'proper method to add frozen wild blueberries in #ice cream#']

Примечание ваша dict переменная является set объектом.


Обновлен фрагмент, как запрошено в комментарии.

Демонстрация:

import re
data = {'fresh air', 'entertainment system', 'ice cream', 'milk', 'dog', 'blood pressure'}
data = {i: i.replace(" ", "_") for i in data}
#pattern = re.compile("("+"|".join(data)+")")
pattern = re.compile(r"\b("+"|".join(data)+r")\b")
text_file = ['is vitamin d in milk enough', 'try to improve quality level by automatic intake of fresh air', 'turn on the tv or entertainment system based on that individual preferences', 'blood pressure monitor', 'I buy more ice cream', 'proper method to add frozen wild blueberries in ice cream']

result = [pattern.sub(lambda x: "#{}#".format(data[x.group()]), i) for i in text_file]
print(result)

Выход:

['is vitamin d in #milk# enough',
 'try to improve quality level by automatic intake of #fresh_air#',
 'turn on the tv or #entertainment_system# based on that individual preferences',
 '#blood_pressure# monitor',
 'I buy more #ice_cream#',
 'proper method to add frozen wild blueberries in #ice_cream#']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...