【问题标题】:How to iterate over a sequence of spaces?如何遍历一系列空间?
【发布时间】:2012-05-23 01:22:54
【问题描述】:

好的,所以我正在尝试获取一个输入文本文件并像 microsoft word 或任何其他文字处理器一样证明它的合理性。我已经得到文本来做字符对齐栏的最后一行。我试图弄清楚如何遍历最后一行中的每个空格并插入一个' ' 以使最后一个达到指定长度。

如果我尝试:

for ' ' in new:
    insert(new,' ',find(' '))

本着 python 教给我的简单风格的精神, 我得到一个不可迭代的错误。因此代码循环中的while。但这只会在第一个空格处插入所有空格。

还有没有办法让这个程序通过单词而不是字符来证明?

我使用“Lorem ipsum...”段落作为我的默认文本。

感谢任何帮助。

完整代码:

inf = open('filein.txt', 'r')
of = open('fileout.txt', 'w')

inf.tell()

n = input('enter the number of characters per line: ')

def insert(original, new, pos):
  #Inserts new inside original at pos.
  return original[:pos] + new + original[pos:] 

try:
    print 'you entered {}\n'.format(int(n))
except:
    print 'there was an error'
    n = input('enter the number of characters per line: ')
else:
    new = inf.readline(n)
    def printn(l):

        print>>of, l+'\n'
        print 'printing to file',
        print '(first char: {} || last char: {})'.format(l[0],l[-1])

    while new != '': #multiple spaces present at EOF
        if new[0] != ' ': #check space at beginning of line
            if new[-1] != ' ': # check space at end of line
                while (len(new) < n):
                    new = insert(new,' ',(new.find(' ')))
                printn(new)

        elif new[0] == ' ':
            new = new.lstrip() #remove leading whitespace
            new = insert(new,' ',(new.find(' ')))
            while (len(new) < n):
                new = insert(new,' ',(new.find(' ')))
            printn(new)

        elif new[-1] == ' ':
            new = new.rstrip() #remove trailing whitespace
            new = insert(new, ' ',(new.rfind(' ')))
            while (len(new) < n):
                new = insert(new,' ',(new.rfind(' ')))
            printn(new)       

        new = inf.readline(n)


    print '\nclosing files...'
    inf.close()
    print 'input closed'
    of.close()
    print 'output closed'

输入:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

如果行长 n == 37

输出:

Lorem ipsum dolor sit amet, consectet
ur adipisicing elit, sed do eiusmod t
magna aliqua. Ut enim ad minim veniam
, quis nostrud exercitation ullamco l
consequat. Duis aute irure dolor in r
cillum dolore eu fugiat nulla pariatu
non proident, sunt in culpa qui offic
ia deserunt mollit anim id est laboru
m                                   .

【问题讨论】:

  • 你能举例输入/输出吗?

标签: python text loops justify


【解决方案1】:

我在理解您想要做什么时遇到了一点麻烦......您似乎可能想要textwrap 模块(http://docs.python.org/library/textwrap.html)。如果这不是您想要的,请告诉我,我会很乐意删除此答案...

编辑

这是你想要的吗?

s="""Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum."""

import textwrap

print textwrap.fill(s,37)

EDIT2

在这种情况下,我会将您的字符串分解为每 N 个块长的子字符串,将这些字符串一个接一个地存储在一个列表中,然后我会在一天结束时使用 "\n".join(list_of_strings)。不过我不会编码,因为我怀疑这是家庭作业。

【讨论】:

  • 这是一个很好的建议,但我认为我不应该使用库函数。为什么,我不太确定。但它在我的程序规范中。
  • @growthndevlpmnt 如果这是家庭作业,你应该这样标记它。
  • 这很好。放学了。这是我的研究导师提出的一个热身挑战。我想它可以归类为家庭作业。不过,感谢您的帮助。
【解决方案2】:
for ' ' in new:
    insert(new,' ',find(' '))

您很想分配给文字。试试这样

for x in new:
    if x == ' ':
        insert(new, x, find(' '))

看看它是否有效?

【讨论】:

  • 或者for x in new: if x == ' ': insert(new,x,find(' '))
  • 这不会遍历行中的每个字符吗?我只想要空间。
  • 它将遍历每个字符并调用 insert() 如果 x 是空格字符。
  • 我明白了。但最后一行仍然比指定的 n 短。无论如何感谢您的帮助。
猜你喜欢
  • 2013-06-21
  • 2017-10-17
  • 2022-06-28
  • 2017-06-18
  • 2023-03-04
  • 1970-01-01
  • 2020-08-20
  • 2016-03-22
  • 2018-10-20
相关资源
最近更新 更多