在python中包装行:打破参数字符串

时间:2013-02-27 02:17:31

标签: python syntax word-wrap

我有一个脚本,其中将str类型的非常长的参数传递给函数:

parser = argparse.ArgumentParser(description='Auto-segments a text based on the TANGO algorithm (Rie Kubota Ando and Lillian Lee, "Mostly-Unsupervised Statistical Segmentation of Japanese Kanji Sequences" (Natural Language Engineering, 9(2):127-149, 2003)).')

我想将此脚本中的行长限制为79个字符,这意味着在相关字符串的中间换行。简单地在79处包装会产生类似这样的东西,这在语法上是不正确的:

parser = argparse.ArgumentParser(description="Auto-segments a text based on 
    the TANGO algorithm (Rie Kubota Ando and Lillian Lee, 'Mostly-Unsupervis
    ed Statistical Segmentation of Japanese Kanji Sequences' (Natural Langua
    ge Engineering, 9(2):127-149, 2003)).")

PEP 8有关于在各种非参数字符串内部位置中断行的指导原则,但是有没有办法在参数字符串的中间断行?

(相关但不那么重要的问题:在(python)脚本中打破自然语言文本中间词的明智/传统方法是什么?)

3 个答案:

答案 0 :(得分:3)

文字字符串可以彼此相邻显示,并将编译为单个字符串。因此:

parser = argparse.ArgumentParser(description="Auto-segments a text based on "
    "the TANGO algorithm (Rie Kubota Ando and Lillian Lee, 'Mostly-Unsupervised "
    "Statistical Segmentation of Japanese Kanji Sequences' (Natural Language "
    "Engineering, 9(2):127-149, 2003)).")

根据需要调整以适应80。

答案 1 :(得分:1)

>>>longarg = "ABCDEF\
GHIJKLMNOPQRSTUVW\
XYZ"

>>>print longarg
ABCDEFGHIJKLMNOPQRSTUVWXYZ

答案 2 :(得分:0)

无论如何,

argparse重新格式化描述字符串,因此如果您使用带有额外空格的多行字符串,它将不会更改结果:

import argparse

parser = argparse.ArgumentParser(description='''Auto-segments a text based on the
    TANGO algorithm (Rie Kubota Ando and Lillian Lee, "Mostly-Unsupervised
    Statistical Segmentation of Japanese Kanji Sequences" (Natural Language
    Engineering, 9(2):127-149, 2003)).''')

args = parser.parse_args()

% test.py -h

usage: test.py [-h]

Auto-segments a text based on the TANGO algorithm (Rie Kubota Ando and Lillian Lee,
"Mostly-Unsupervised Statistical Segmentation of Japanese Kanji Sequences" (Natural
Language Engineering, 9(2):127-149, 2003)).

optional arguments:
  -h, --help  show this help message and exit