根据Python中的索引列表减去文本文件中的字符串

问题描述 投票:1回答:1

我有一个.txt文件,我想提取其中的某些位置之间的文本。为此,我列出了位置索引,因此可以对这些位置进行子交易以获取文本。并将其附加到其他.txt文件。

例如(伪代码):

indexList = [188, 1089, 364, 5697, 2, 5230, 2683, 2956]

with open(str(mytxtfile), 'r') as f:
     for line in f:
        subtract the text from location 2956 with the text of location 2683.
        Now append this to a txt variable.
        Loop this over for the entire list. 
python string text
1个回答
1
投票

您可以使用元组列表表示开始/结束字符位置。您可以使用fileDescriptor.read()将文件的全部内容读入字符串变量中。然后,您可以使用字符串切片功能以特定的偏移量(即x = "abcdefg"; x[2:5] is "cde")获取文本。

indexList = [(188, 1089), (364, 5697), (2, 5230), (2683, 2956)]

with open(str(mytxtfile), 'r') as f:
    contents = f.read()

textFragments = []
for start,end in indexList:
    textFragments.append(contents[start:end])

# textFragments[0] = text between positions 188 and 1089
# textFragments[1] = text between positions 364 and 5697
# so forth

如果要将所有这些片段都放在一个字符串变量中,则可以使用join将它们连接起来,如下所示:''.join(textFragments)

© www.soinside.com 2019 - 2024. All rights reserved.