【问题标题】:Sort paragraphs in a text file alphabetically using Python使用 Python 按字母顺序对文本文件中的段落进行排序
【发布时间】:2016-01-21 19:59:24
【问题描述】:

我需要根据每个段落中使用的文件名按字母顺序对段落进行排序。这是一个示例(文本文件中大约有 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 #对段落进行排序(标识符与顶部的文本文件同名,但文本文件在不同的子文件夹中,所以我认为使用标识符会更好)。

【问题讨论】:

  • 好吧,我什至不知道如何开始,因为我是 Python 初学者
  • 是的,我认为初学者的问题没有错。

标签: python sorting text-files paragraph


【解决方案1】:

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

这可以使用

来实现
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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多