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

问题描述 投票:3回答:3

我有一个脚本,其中一个非常长的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)脚本中打破自然语言文本中间词的明智/传统方式?)

python syntax word-wrap
3个回答
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
投票
>>>longarg = "ABCDEF\
GHIJKLMNOPQRSTUVW\
XYZ"

>>>print longarg
ABCDEFGHIJKLMNOPQRSTUVWXYZ

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
© www.soinside.com 2019 - 2024. All rights reserved.