是否有更好的方法来解决这个问题,最好不要通过模块。
问题是:
文字处理。你厌倦了在电子邮件包装上看到线条 因为人们为邮件阅读器输入太长的行 应用。创建一个程序来扫描所有行的文本文件 超过80个字符。对于每个违规行,找到 在80个字符之前最接近的单词并在那里打破行,插入 剩余的文本到下一行(并按下前一行 排队一)。完成后,应该没有更长的行 超过80个字符。
让9-16.txt的内容为:
Text Processing. You are tired of seeing lines on your e-mail wrap because people type lines that are too long for your mail reader application. Create a program to scan a text file for all lines longer than 80 characters. For each of the offending lines, find the closest word before 80 characters and break the line there, inserting the remaining text to the next line (and pushing the previous next line down one). When you are done, there should be no lines longer than 80 characters.
我的计划
f=open('9-16.txt','r')
lis=[]
def ding(a):
if len(a)<=80:
lis.append(a)
return
else:
if a[79]==' ':
lis.append(a[:80])
ding(a[80:])
elif a[79]!=' ':
ind=a.rfind(' ',0,79)
lis.append(a[:ind+1])
ding(a[ind+1:])
for x in f:
if len(x)>80:
ding(x)
else:
lis.append(x)
ty=open('9-16o.txt','w')
for x in lis:
if x[-1]==' ':
x=x[:-1]+'\n'
else :
x+='\n'
ty.write(x)
f.close()
ty.close()
9-16o.txt现在包含:
Text Processing. You are tired of seeing lines on your e-mail wrap because
people type lines that are too long for your mail reader application. Create a
program to scan a text file for all lines longer than 80 characters. For each
of the offending lines, find the closest word before 80 characters and break
the line there, inserting the remaining text to the next line (and pushing the
previous next line down one). When you are done, there should be no lines
longer than 80 characters.
答案 0 :(得分:8)
这是一个使用正则表达式的相当简单和简洁的解决方案,它可能不适用于您的作业,但它应该明确为什么限制模块使用是不可取的:
import re
s = 'Text Processing. You are tired of seeing lines on your e-mail wrap because people type lines that are too long for your mail reader application. Create a program to scan a text file for all lines longer than 80 characters. For each of the offending lines, find the closest word before 80 characters and break the line there, inserting the remaining text to the next line (and pushing the previous next line down one). When you are done, there should be no lines longer than 80 characters.'
print '\n'.join(line.strip() for line in re.findall(r'.{1,80}(?:\s+|$)', s))
结果:
Text Processing. You are tired of seeing lines on your e-mail wrap because
people type lines that are too long for your mail reader application. Create a
program to scan a text file for all lines longer than 80 characters. For each of
the offending lines, find the closest word before 80 characters and break the
line there, inserting the remaining text to the next line (and pushing the
previous next line down one). When you are done, there should be no lines longer
than 80 characters.
您的示例文本是一行,您可能实际上想要使用以下内容:
def split_lines(text):
lines = text.split('\n')
regex = re.compile(r'.{1,80}(?:\s+|$)')
return '\n'.join(s.rstrip() for line in lines for s in regex.findall(line))