我正在编写一个将每行限制为一定长度的程序。
这是我到目前为止得到的,我几乎完成了,但我仍然需要剪掉每一行,但我无法弄清楚。
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
wr.width = lLength
wr.expand_tabs = True
for lines in wraped:
print(lines)
编辑:
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
if (lLength > 10) or (lLength < 20):
print("\nYour file contains the following text: \n" + file)
#=========================================================================
wr = textwrap.TextWrapper(width=lLength)
wraped = wr.wrap(file)
print("\n\nHere is your output formated to a max of", lLength, "characters per line: ")
for lines in wraped:
print(lines)
main()
输出应该是这样的一个例子。如果指定的文件包含此文本:
hgytuinghdt #here the length is 11
ughtnjuiknshfyth #here the length is 16
nmjhkaiolgytuhngjuin #here the length is 20
并且 lLength 被指定为 15 那么这应该打印出来:
hgytuinghdt
ughtnjuiknshfyt
h
nmjhkaiolgytuhng
juin