Как создать словарь из текста? - PullRequest
0 голосов
/ 21 октября 2018

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

['text', 'text', 'text', 'text', 'text','text', 'text', 'Country Code', '11111', 'Country Location', 'North', 'Date', '18-03-1878', text','text','text', 'Population': '1289028', 'text', 'text', 'Government', 'Monarchy', 'text', 'text', 'Religion:', 'Catholic']

Мне нужна конкретная информация, такая как местоположение страны, код страны и дата.Дело в том, что положение этих строк варьируется от текста к тексту, поэтому мне нужна функция, которая сначала находит эту информацию в тексте, помещает ее в качестве ключа моего словаря и принимает следующий элемент в тексте в качестве значения.Я надеялся получить такой результат:

{"Country Code": "11111", 
 "Country Location": "North", 
 "Date": "18-03-1878"
 "Population": "1289028"  
 "Religion:" "Catholic"}

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

1 Ответ

0 голосов
/ 21 октября 2018

Если вам не важна эффективность и ключи единообразны, вы можете просто написать цикл.

your_list = ['text', 'text', 'text', 'text', 'text','text', 'text', 'Country Code', '11111', 'Country Location', 'North', 'Date', '18-03-1878', 'text','text','text', 'Population', '1289028', 'text', 'text', 'Government', 'Monarchy', 'text', 'text', 'Religion:', 'Catholic']

our_dict = {}

for idx, word in enumerate(your_list):
    if 'Country Code' in word:
        our_dict['Country Code'] = your_list[idx+1]
    if 'Country Location' in word:
        our_dict['Country Location'] = your_list[idx+1]
    if 'Date' in word:
        our_dict['Date'] = your_list[idx+1]
    if 'Population' in word:
        our_dict['Population'] = your_list[idx+1]
    if 'Religion' in word:
        our_dict['Religion'] = your_list[idx+1]

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

for idx, word in enumerate(your_list):
    if len(word.strip(' ')) > 0:
        if 'Country Code' in word:
            our_dict['Country Code'] = your_list[idx+1]
        if 'Country Location' in word:
            our_dict['Country Location'] = your_list[idx+1]
        if 'Date' in word:
            our_dict['Date'] = your_list[idx+1]
        if 'Population' in word:
            our_dict['Population'] = your_list[idx+1]
        if 'Religion' in word:
            our_dict['Religion'] = your_list[idx+1]

Сокращенное решение:

#Create a list of items you are interested in (this is a set - only uniques)
itemstofind = {'Country Code', 'Country Location', 'Date', 'Population', 'Religion:'}

# use a dict comprehension to find the items and take next item in the list
# assumes there is no error in the data
d = {item:longlist[ind+1] for ind, item in enumerate(longlist) if item in itemstofind}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...