Расшифровка текстового файла с использованием списков в Python - PullRequest
0 голосов
/ 05 ноября 2019

Я закодировал это предложение:

Это удивительный «абстракция» И это: конец этого удивительного абстракции.

этому:

1 2 34 "5" 6 7: 2 8 9 10 7 4 5.

Соответствующая индексная таблица (в виде текстового файла):

word,index
This,1
is,2
an,3
amazing,4
abstract,5
AND,6
this,7
the,8
end,9
of,10

Теперь я хочу перейти от этих чисел:'1 2 3 4 "5" 6 7: 2 8 9 10 7 4 5.' соответствующим словам, используя таблицу индексов.

Я использовал этот код, чтобы открыть текстовый файл таблицы индексов в виде нарезанного списка:

index_file = open("decompress.txt", "r")

content_index = index_file.read().split()
print(content_index)

вывод:

['word,index', 'This,1', 'is,2', 'an,3', 'amazing,4', 'abstract,5', 'AND,6', 'this,7', 'the,8', 'end,9', 'of,10']

Затем я нарезал каждый элемент на новый список с помощью этого кода:

for line in content_index:
    fields = line.split(",")

вывод:

['word', 'index']
['This', '1']
['is', '2']
['an', '3']
['amazing', '4']
['abstract', '5']
['AND', '6']
['this', '7']
['the', '8']
['end', '9']
['of', '10']

Я пытался декодировать числа, используя поля [0] и поля [1] и циклы, но у меня ничего не получилось. Любая помощь будет принята с благодарностью!

Ответы [ 2 ]

0 голосов
/ 05 ноября 2019

Для этого экземпляра вы можете использовать регулярное выражение из re module и несколько значений .

При первом импорте re и получить все строки в списке:

import re

with open('decompress.txt') as f:
    lines = f.readlines()
#>> lines
# ['word,index\n', 'This,1\n', 'is,2\n', 'an,3\n', 'amazing,4\n', 
#  'abstract,5\n', 'AND,6\n', 'this,7\n', 'the,8\n', 'end,9\n', 'of,10']

После этого используйте re.search с шаблоном (.*) - выберите anythink, , - до комы и (\d+) - несколько цифр после. В этом случае пропустите первую строку документа.

parsed_lines = [re.search(r'(.*),(\d+)', line) for line in lines if 'index' not in line]

И, наконец, создайте словарь с индексом, а текст - значением.

fields = {int(line_match.group(2)): line_match.group(1) for line_match in parsed_lines}
# {1: 'This', 2: 'is', 3: 'an', 4: 'amazing', 5: 'abstract', 
#  6: 'AND', 7: 'this', 8: 'the', 9: 'end', 10: 'of'}

UPD: ИЛИ к спискуна втором шаге:

parsed_lines = [re.search(r'(.*),\d+', line).group(1) for line in lines if 'index' not in line]
0 голосов
/ 05 ноября 2019

Прежде всего, лучше использовать dict и заменить ваш код:

for line in content_index:
    fields = line.split(",")

на:

fields = {}
for line in content_index:
    word, number = line.split(',')
    fields[number] = word

Затем вы можете использовать регулярные выражения для простой замены определенных шаблонов (втвой случай - числа) любыми другими строками. Регулярное выражение для поиска номера будет \d+, где \d означает digit, а + - для one or more Итак:

import re

original_string = ' 1 2 3 4 "5" 6 7: 2 8 9 10 7 4 5. '

def replacement(match):
    """
    This function accepts regular expression match and returns corresponding replacement if it's found in `fields`
    """
    return fields.get(match.group(0), '')  # Learn more about match groups at `re` documentation.

result = re.sub(r'\d+', replacement, original_string)  # This line will iterate through original string, calling `replacement` for each number in this string, substituting return value to string.

Итак, окончательный код будет:

import re

fields = {}

with open('decompress.txt') as f:
    for line in f.readlines():
        word, number = line.split(',')
        fields[number] = word

original_string = ' 1 2 3 4 "5" 6 7: 2 8 9 10 7 4 5. '

def replacement(match):
    """
    This function accepts regular expression match and returns corresponding replacement if it's found in `fields`
    """
    return fields.get(match.group(0), '')

result = re.sub(r'\d+', replacement, original_string)
print(result)

Вы можете узнать больше о регулярных выражениях в документации по Python о библиотеке re. Это очень мощный инструмент для обработки и анализа текста.

...