我试图让它读取文件并将行转换为单词然后将单词附加到给定长度的行。并返回文本。这是我到目前为止所做的。
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()
当我运行代码时,它似乎跳过了前两个函数并且没有返回任何文本。
如果你知道我哪里出错了,请告诉我。
谢谢。
答案 0 :(得分:0)
这使用了来自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')
答案 1 :(得分:0)
另外,非常有趣的读物是使用动态编程实现文本对齐。麻省理工学院在网上有一些很好的关于这个主题的演讲幻灯片,但this堆栈线程有大部分内容。它类似于乳胶用于使所有文本看起来“漂亮”的算法。它扩展了您对文本换行的想法,并添加了对齐功能(它添加了空格以使其看起来尽可能最好)。
答案 2 :(得分:0)
您的代码确实跳过前两个函数,它只定义它们。您需要在之后的某个地方调用它们,就像使用main()
函数一样。没有明显的输出,因为代码永远不会对main()
函数返回的行做任何事情(例如print
)。
您可能需要考虑使用Python的内置模块textwrap
来执行此类文本处理。这是一个简单的例子来说明它的用法:
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()