(python)将输出格式化为变量&优化编写糟糕的脚本

(python)将输出格式化为变量&优化编写糟糕的脚本,python,formatting,nltk,Python,Formatting,Nltk,我将以下脚本修改为samplebias[在samplebias,非常有用,谢谢:]发现并编写的我的原始需求: import textwrap from nltk.corpus import wordnet as wn POS = { 'v': 'verb', 'a': 'adjective', 's': 'satellite adjective', 'n': 'noun', 'r': 'adverb'} def info(word, pos=None): for i

我将以下脚本修改为samplebias[在samplebias,非常有用,谢谢:]发现并编写的我的原始需求:

import textwrap
from nltk.corpus import wordnet as wn

POS = {
    'v': 'verb', 'a': 'adjective', 's': 'satellite adjective', 
    'n': 'noun', 'r': 'adverb'}

def info(word, pos=None):
    for i, syn in enumerate(wn.synsets(word, pos)):
        syns = [n.replace('_', ' ') for n in syn.lemma_names]
        ants = [a for m in syn.lemmas for a in m.antonyms()]
        ind = ' '*12
        defn= textwrap.wrap(syn.definition, 64)
        print 'sense %d (%s)' % (i + 1, POS[syn.pos])
        n1=str('definition: ' + ('\n' + ind).join(defn))
        n2=str('  synonyms:', ', '.join(syns))
        if ants:
            n3=str('  antonyms:', ', '.join(a.name for a in ants))
        if syn.examples:
            n4=str('  examples: ' + ('\n' + ind).join(syn.examples))
        try:
            resp = ("From dictionary:\n%s\n%s\n%s\n%s") %(n1, n2, n3, n4)
        except:
            try:
                resp = ("From dictionary:\n%s\n%s\n%s") %(n1, n2, n3)
            except:
                try:
                    resp = ("From dictionary:\n%s\n%s") %(n1, n2)
                except:
                    resp = ("Data not available...")
        print
        return resp
但是,我可以看出我并没有很好地修改它,因为它只是包装在try/except块中。但就我的一生而言,我想不出更好的方法来做这件事,仍然是以抽象的方式学习python。我需要将其格式化为一个变量,该变量在写入文件时包含\n作为每行的分隔符。有什么办法可以让我做得更好,而不必列出那些似乎正在发生的事情吗

-定义日出

从字典:

定义:一天中的第一缕曙光

“同义词:”,“黎明,黎明,早晨,极光,第一缕曙光,黎明,破晓,破晓,黎明,黎明,黎明,黎明,黎明,日出,日出,乌鸦”

“反义词:”,“日落”

我们黎明前起床 他们一直聊到早上


谢谢

不要为每行创建字符串,只需从一开始就将文本附加到输出变量

resp = 'From dictionary:\ndefinition: ' + ('\n' + ind).join(defn) +'\n'
resp += '  synonyms:' + ', '.join(syns) +'\n'
if ants:
    resp += '  antonyms:' + ', '.join(a.name for a in ants)) +'\n'
if syn.examples:
    resp += '  examples: ' + ('\n' + ind).join(syn.examples)) +'\n'

谢谢这很好用,也很容易理解。还帮助理解str.join的用法,因为在我的教程中有一些例子;但我不知道什么时候需要它。再次感谢: