我正在编写一个程序,将每一行限制为一定的长度。
这是我到目前为止所做的,我差不多完成但是我仍然需要削减每一行,但我无法弄明白。
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
答案 0 :(得分:3)
wr = textwrap.TextWrapper()
应为wr = textwrap.TextWrapper(width=length, expand_tabs=True)
然后,您应该删除wr.width = lLength
和wr.expand_tabs = True
。它们应该在wr.wrap()
被调用之前运行,但是由于可以使用TextWrapper
构造函数中的关键字参数来设置它,如最上面所示,它们可以被删除。
TextWrapper.fill
, PS :for lines in wraped: print(lines)
可以替换为print(wraped)
。
答案 1 :(得分:0)
试试这个:
line = 'nmjhkaiolgytuhngjuin'
n = 5 # set the width here
a = [line[i:i+n] for i in range(0, len(line), n)]
print ("\n".join(a))
答案 2 :(得分:0)
这可能会对您有所帮助:
Sheets("Sheet2").Rows(1 & ":" & Sheets("Sheet2").UsedRange.Rows.Count).ClearContents