-4

嗨,我想创建将像这样工作的应用程序:来自文件的字符串,例如:

AAAAa aaaaa
bb bbbbbbbbbbbbb
ccccccccccccc

当 x 是行的最大长度时,将被 x 包裹,因此对于 x = 10,它看起来像

AAAAa aaaa
aabb bbbbb   
....

我已经尝试过这段代码,但它不起作用

def length(x):
    return x
t = open("text.txt", "r")
x = int(input("Enter length: \n"))
length(x)
for line in t:
     print(line.strip())
     if int(len(line) >= length(x)):
          print("\n")
t.close()

这段代码正在做其他事情,你能帮帮我吗?:)

4

3 回答 3

1
>>> t='''AAAAa aaaaa
bb bbbbbbbbbbbbb
ccccccccccccc'''
>>> x = int(raw_input("Enter length: "))
>>> print '\n'.join(t.replace('\n', '')[i:i+x] for i in range(0, len(x), x))
AAAAa aaaa
abb bbbbbb
bbbbbbbccc
cccccccccc

所以:

with open("text.txt") as f:
    t = f.read()
x = int(input("Enter length: \n"))
print '\n'.join(t.replace('\n', '')[i:i+x] for i in range(0, len(x), x))
close t
于 2013-10-19T20:41:18.350 回答
0

似乎他们想要获取文本文件并遍历每个字符,直到到达 X 然后开始一个新行继续打印文本,直到再次到达 x。

这需要修改并且未经测试

def textiterator(xinput):
    counter = 0
    transformedtext = ''
    textfromfile = ''
    textfile = open('youroriginaltextfile.txt', 'r')

    for eachline in textfile:
            textfromfile = textfromfile + eachline

    while counter <= len(textfromfile):

        if counter not equal to % of xinput: ##modulus operator needs to be added for multiple of xinput
            transformedtext = transformedtext + textfromfile[counter]
            counter = counter + 1

        else:
            transformedtext = transformedtext + '\n'


    return transformedtext
于 2013-10-19T20:11:40.887 回答
0

这应该这样做:

def in_groups(seq, n):
    # see http://docs.python.org/2/library/itertools.html#recipes
    return zip(*[iter(seq)] * n)

l = int(raw_input("Enter length: "))
with open("text.txt") as f:
    contents = f.read()
print '\n'.join(''.join(t) for t in in_groups(contents.replace('\n', ''), l))
于 2013-10-19T20:13:18.930 回答