我有一个.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.
您可以使用元组列表表示开始/结束字符位置。您可以使用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)