2013-02-27 69 views
1

我在這很長str類型的參數傳遞給函數的腳本:包裝線在python:打破一個參數字符串

 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有打破各種非參數字符串內部位置線指引,但有沒有辦法打破行參數字符串的中間?

(相關但不太重要的問題:什麼是打破(蟒蛇)腳本中的自然語言文字中間字一個明智的/常規的方式)

回答

1

文字字符串可以彼此相鄰的出現,並將編譯爲單個字符串。因此:

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

​​反正重新格式化描述字符串,因此如果使用多行字符串多餘的空格也不會改變結果:

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