5

我有一个脚本,其中一个很长的类型参数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)脚本中打破自然语言文本中间词的明智/传统方法是什么?)

4

3 回答 3

5

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

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。

于 2013-02-27T02:22:00.087 回答
1
>>>longarg = "ABCDEF\
GHIJKLMNOPQRSTUVW\
XYZ"

>>>print longarg
ABCDEFGHIJKLMNOPQRSTUVWXYZ
于 2013-02-27T02:21:22.160 回答
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
于 2013-02-27T02:35:04.823 回答