1

I am trying to get it to read the file and convert the lines to words then append the word to a line of a given length. and return the text. This is what I have so far.

def file(file_name):
    ''' gets users file and checks its validity'''
    try:
       open(file_name).readlines()
    except IOError:
        print('File not found')
    else:
        file = file_name.split()
    return file

def column_length(width):
    '''gets column width and checks its validity'''
    try:
        if int(width) >= 1:
    return int(width) 
    else:
        print('illegal value')
    except ValueError:
        print('Illegal value')


def main():
    file_name = input('Input file name? ')
    width = input('column width? ')
    lines = []
    line = ''
    for i in file_name:
        if len(i) + len(line) > int(width):
            lines.append(line)
            line = ''
            line = line + i + ' '
        if i is file_name[-1]: lines.append(line)
    return '\n'.join(lines)


if __name__ == "__main__": 
    main()

When I run the code, it seems to skip out the first two functions and doesn't return any text.

If you know where I'm going wrong please let me know.

Thank you.

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

0

this uses a great answer from here

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

with open('in_file.txt') as in_file, open('out_file.txt', 'w') as out_file:
    for in_line in in_file:
        for out_line in chunks(in_line, width)
            out_file.write(out_line + '\n')
Community
  • 1
  • 1
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42
0

Also, very interesting read is the implementation of text justification using dynamic programing. MIT has some great lecture slides online about the subject but this stack thread has most of it. It's similar to the algorithm latex uses to make all text look "pretty". It expands on your idea of text wrapping and adds the feature of justification (it adds whitespaces to make it look as best as possible).

Community
  • 1
  • 1
ZekeDroid
  • 7,089
  • 5
  • 33
  • 59
0

Your code does skip the first two functions, it only defines them. You need to call them from somewhere afterwards, like you did with themain() function. There's no apparent output because the code never does anything with the lines themain()function returns (such asprintthem).

You might want to consider using Python's built-in moduletextwrapto do this sort of text processing. Here's a simple example illustrating its use:

import os
import textwrap

def get_file_name():
    """ Get file name and checks its validity. """
    file_name = input('Input file name? ')
    if not os.path.isfile(file_name):
        raise FileNotFoundError('"%s"' % file_name)
    return file_name

def get_column_width():
    """ Get column width and checks its validity. """
    width = int(input('Column width? '))
    if width < 1:
        raise ValueError('column width must be greater than zero')
    return width

def line_wrap(file_name, width):
    """ Read blank line delimited paragraphs of text from file and wrap them to
        the specified width.
    """
    wrapped_lines = []
    with open(file_name) as input_file:
        lines = ''
        for line in input_file:
            lines += line
            if not line.rstrip():  # blank line?
                wrapped_lines.extend(textwrap.wrap(lines, width) + ['\n'])
                lines = ''
    if lines:  # last paragraph need not be followed by blank line
        wrapped_lines.extend(textwrap.wrap(lines, width))
    return wrapped_lines

def main():
    file_name = get_file_name()
    width = get_column_width()
    wrapped_lines = line_wrap(file_name, width)
    print('\n'.join(wrapped_lines))

if __name__ == "__main__":
    main()
martineau
  • 119,623
  • 25
  • 170
  • 301