使用Python中的列表解码文本文件



我编码了这句话:

这是一个令人惊叹的"摘要",这是这个令人惊叹的摘要的结尾。

到此:

1 2 3 4"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']

我尝试使用fields[0]、fields[1]和for循环来解码数字,但没有成功。如有任何帮助,我们将不胜感激!

首先,最好使用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)

您可以在关于re库的Python文档中了解有关正则表达式的更多信息。这是一个非常强大的文本处理和解析工具。

对于这个例子,您可以使用re-module中的regex和几个composition。

在第一次导入时,重新并将所有行列出:

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

之后使用模式为(.*)re.search-选择任意思维,,-昏迷前,(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:OR在第二步中列出:

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

最新更新