您可以使用標準textwrap
module:
import textwrap
txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
print '\n'.join(textwrap.wrap(txt, 20, break_long_words=False))
首先,閱讀文件,你應該使用with
建設:
with open(filename, 'r') as f:
lines = f.readlines()
def wrap(line):
broken = textwrap.wrap(line, 20, break_long_words=False)
return '\n'.join(broken)
wrapped = [wrap(line) for line in lines]
但你說,你不希望使用內置textwrap,但你自己做,所以這裏是沒有進口的解決方案:
import textwrap
lorem = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus ac commodo libero, at dictum leo. Nunc convallis est id purus porta,
malesuada erat volutpat. Cras commodo odio nulla. Nam vehicula risus id lacus
vestibulum. Maecenas aliquet iaculis dignissim. Phasellus aliquam facilisis
pellentesque ultricies. Vestibulum dapibus quam leo, sed massa ornare eget.
Praesent euismod ac nulla in lobortis.
Sed sodales tellus non semper feugiat."""
def wrapped_lines(line, width=80):
whitespace = set(" \n\t\r")
length = len(line)
start = 0
while start < (length - width):
# we take next 'width' of characters:
chunk = line[start:start+width+1]
# if there is a newline in it, let's return first part
if '\n' in chunk:
end = start + chunk.find('\n')
yield line[start:end]
start = end+1 # we set new start on place where we are now
continue
# if no newline in chunk, let's find the first whitespace from the end
for i, ch in enumerate(reversed(chunk)):
if ch in whitespace:
end = (start+width-i)
yield line[start:end]
start = end + 1
break
else: # just for readability
continue
yield line[start:]
for line in wrapped_lines(lorem, 30):
print line
編輯我不喜歡上面的版本,它對我的口味有點醜陋和非pythonic。以下是另一種:
def wrapped_lines(line, width=80):
whitespace = set(" \n\t\r")
length = len(line)
start = 0
while start < (length - width):
end = start + width + 1
chunk = line[start:end]
try:
end = start + chunk.index('\n')
except ValueError: # no newline in chunk
# we iterate characters from the end:
for i, ch in enumerate(reversed(chunk)):
if ch in whitespace:
end -= i # we have our end on first whitespace
break
yield line[start:end]
start = end + 1
yield line[start:]
你應該看看:https://docs.python.org/3.4/library/textwrap.html –
由於你問的算法而不是代碼或語言:基本上,你想看看字符那就是start + n,如果它是空白的,就換行;如果不是空格,請看start + n - 1;如果這不是空格,請查看start + n - 2 ...將有代碼中優化此方法。 –