我知道还有许多其他帖子与此有关>
所以我使用以下方式从文本文件中加载单词:
file = open("words.txt","r").readlines()
试图以:
之类的形式打印它们Cat Dog Fish
Log Mouse Rat
Horse Cow Meow
理想情况下,我尝试使用循环,但无法弄清楚如何在三个印刷后添加 n。
在必要时使用计数器添加新行:
for num, word in enumerate(file, 1):
print word.strip(),
if num % 3 == 0:
print
理想情况下,从文件中读取行的最佳方法是不要将它们全部读取到一个列表中(除非您明确需要这样需要),并使用上下文管理器确保文件正确关闭:
with open('words.txt', 'r') as f:
for num, word in enumerate(f, 1):
print word.strip(),
if num % 3 == 0:
print
您可以使用表模块
from tabulate import tabulate
f = open("words.txt","r").readlines()
words = list(map(str.split, f))
print tabulate(words)
输出:
In [18]: print tabulate(words)
--- ----- ----
Cat Dog Fish
Log Mouse Rat
Foo Bar Baz
--- ----- ----
但是,如果您的单词中的每行有一个单词。
from tabulate import tabulate
f = open("words.txt","r").readlines()
f1=[f[i:i+3] for i in range(0,len(f),3)]
print tabulate(f1)
假设您的文件每行包含一个单词:
lines = open("words.txt","r").readlines()
words = list(map(str.strip, lines))
for i in range(0, 9, 3):
print(' '.join(words[i:i+3]))
首先,我像您一样阅读了行,然后删除尾随的新线以获取单词,然后以3个步骤走在列表中,然后打印每个由空间加入的三倍。
毕竟,您只想添加足够的空间以使每行的每个单词对齐,但最小的空间可能。同样,每行必须对齐,但这不是问题。
要配上空格,您首先必须找到该行最大的单词。然后,您可以定义所需的行宽度。使用此宽度,您将能够为每个单词添加缺失的空间。
假设您的单词存放在二维列表中:words_list = [[Cat, Dog, Fish], [Log, Mouse, Rat]]
。
我们假设每个子名单都有相同的长度。现在,您必须找到每一行的最大词。为此,我们会迭代单词,并找到最大的单词:
# This list contains the maximum width of the row
# We set it to [0, 0, ..., 0] to start (in fact, no length will
# be negative)
# Every sublist have the same length = len(list1)
widths = [0 for i in range len(words_list[1])]
# Now, we'll iterate on the lines, and find the biggest width
for line in words_list:
for biggest, word in zip(widths, line):
# check if this word will expand the row
if len(word) > biggest:
biggest = len(word)
现在,宽度包含每行的最大长度。现在,让我们打印它们。请注意,我们必须在每个最大宽度中添加1个,否则会有一些错误。
for line in words_list:
text_line = ""
for length, word in zip(widths, line):
text_line += word
text_line += " " * (length - len(word) + 1)
print(text_line)