Как перенести заголовки и списки простого текста в объект словаря Python? - PullRequest
1 голос
/ 14 мая 2019

Мой вопрос:

Я хочу разобрать простой текст с заголовками и списками в один объект Python, где заголовки - dict ключ, а списки - listценностей.Текст показан ниже:

Playing cricket is my hobby:
(a) true.
(b) false.
Furthermore, the heading does not include: 
(a) Singlets.
(b) fabrics.
(c) Smocks.

Мой желаемый вывод:

{"Playing cricket is my hobby:":["(a)true.","(b)false."],"Furthermore, the heading does not include:":["(a) Singlets.","(b) Garments.","(c) Smocks."]} 

Что я сделал

Я в первую очередьпреобразовать текст в список строк:

plaintxtlist=['Playing cricket is my hobby:','(a) true.','(b) false.','Furthermore, the heading does not include:','(a) Singlets.',' (b) fabrics.','(c) Smocks.']

Я попытался преобразовать приведенный выше список в словарь, ключами которого являются индекс заголовка, значения и списки текста.Вот код:

import re
data = {} #dictonary 
lst = []    #list
regalter=r"^\s*\(([^\)]+)\).*|^\s*\-.*"   #regex to identify (a)(A) or - type of lines 
j=0
sub = [] #list
plaintxtlist=['Playing cricket is my hobby:','(a) true.','(b) false.','Furthermore, the heading does not include:','(a) Singlets.',' (b) fabrics.','(c) Smocks.']
for i in plaintxtlist:                #the data in text files are converted to list of strings and passed to code 
    if sub:
        match = re.match(regalter, i)   # pattern matching using regex
        if match:
            sub.append(i)             #if the line containes (a)or(A) it will be appended to list called sub
        else:
            j=j+1                  #each list of lines will have value from 0 n (n is the last line) 
            sub = [i]              #list of text will be appended to list called sub
        data[str(j)] = sub         # here the sub list will be added to dictonary named data with o,1,2,3 respectively we are laster converting that to string      
    else:
        if sub:
            data[str(j)] = sub  #else if sub the content in the sublist will be appended to dictonary named data 
        sub = [i]                   #each line will be appended to sub list
        data[str(j)] = i           # if there is no match with regex the pain text will be appended to dictonary 
print(data)                         #print the 

И вывод из кода ниже:

{"0":["Playing cricket is my hobby:","(a)true.","(b)false."],"1":["Furthermore, the heading does not include:","(a) Singlets.","(b) Garments.","(c) Smocks."]}

1 Ответ

0 голосов
/ 14 мая 2019

Вам не нужно сначала переносить каждую строку, чтобы вписаться в список. Чтобы упростить его, вы можете сначала упорядочить необработанный текстовый контент по regex, а затем проанализировать его в dictionary, который вы хотите.

Вы можете узнать отношение группировки, указав, что текстовое содержимое идет перед "точкой", за которой не следует "(" в следующей строке .

Предположим, текстовое содержимое сохранено в файле с именем a_text_file.txt. Полный код находится здесь:

import re

with open('a_text_file.txt') as f:
   s = f.read()

pattern = re.compile(r'[\w\s\().:,]+?\.(?!\n\()')
data = dict()

for m in re.findall(pattern, s):

    # Group the raw content by `regex`,
    # and fit each line into a list
    group = m.strip()
    lst = group.split('\n')

    # Strip out spaces in `key` and `value`
    key = lst[0].strip()
    value = [i.strip() for i in lst[1:]]

    # Fit into the final output
    data.update({key: value})

print(data)

Окончательный вывод:

{'Playing cricket is my hobby:': ['(a) true.', '(b) false.'], 'Furthermore, the heading does not include:': ['(a) Singlets.', '(b) fabrics.', '(c) Smocks.']}
...