使用Python按字母顺序对文本文件中的段落进行排序

时间:2016-01-21 11:18:34

标签: python sorting text-files paragraph

我需要根据每个段落中使用的文件名按字母顺序对段落进行排序。下面是一个示例(文本文件中有大约200个这样的段落):

------------------------------------------------------------------
L:hwqw\se\hf8594.txt

File Creation Date:            September 07, 2004
Identifier #:                  hf8594.tif
Image Pixels (meters):         1.25
Format:                        8 bit TIFF

------------------------------------------------------------------
L:hhtk\ha8421.txt

File Creation Date:            September 07, 2004
Identifier #:                  ha8421.tif
Image Pixels (meters):         1.25
Format:                        8 bit TIFF

现在我需要根据Identifier #对段落进行排序(标识符与顶部的文本文件同名,但文本文件位于不同的子文件夹中,所以我认为最好使用标识符)。

1 个答案:

答案 0 :(得分:3)

拆分段落字符串以获取列表中的每个段落。

这可以使用

来实现
paragraph_sep = "------------------------------------------------------------------\n"
paragraphs = paragraph_str.split(paragraph_sep)[1:]

从每个段落项中提取标识符。

可以使用regular expressions

完成此操作
import re
s = 'Identifier #:                  hf8594.tif'
comp = re.compile("Identifier #: \s* (.*tif)")
a = re.search(comp, s)
a.groups()
=> ('hf8594.tif',)

使用标识符对段落列表进行排序。

请注意,您可以轻松传递一个功能,将键设置为排序功能。

comp = re.compile("Identifier #: \s* (.*tif)")
def get_id_from_string(s):
    ids = re.search(comp, s)
    return ids[0]
paragraphs.sort(key=get_id_from_string)

重建字符串

使用sep.join(paragraphs)

您现在有不同的步骤,希望它有所帮助。

相关问题