我有一个包含40个字的文本文件,例如one two three ... forty
。所有单词都是彼此之间,不包含逗号。我需要将它们打印到屏幕上或彼此相邻的另一个文件中,并用逗号隔开(例如:one, two, three,
...),并且还要每十(10)或七(7)个包裹一次话。
这是我的代码,无法正常工作:
import textwrap
flag = 1
comma = ', '
with open('drop_words.txt', encoding='utf-8') as file:
content = file.read()
content = content.split()
words = comma.join(content)
if len(content)%7 == 0:
print(words, '\n')
有人可以帮忙吗? 谢谢。
答案 0 :(得分:1)
drop_words.txt:
one
two
three
four
然后:
with open('drop_words.txt', encoding='utf-8') as file:
content = file.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
print(", ".join(content), end = '')
输出:
one, two, three, four
编辑:
,如果将单词包装在一起意味着将它们分组,则可以使用grouper,例如:
import itertools as IT
def grouper(n, iterable):
iterable = iter(iterable)
return iter(lambda: list(IT.islice(iterable, n)), [])
with open('list.txt', encoding='utf-8') as file:
content = file.readlines()
content = [l.strip() for l in content if l.strip()]
print(", ".join(content))
grouping = ", ".join(content)
#creating a list out of the comma separated string
grouping = grouping.split(",")
# grouping the two elements
print(list(grouper(2, list(grouping))))
输出:
one, two, three, four
[['one', ' two'], [' three', ' four']]
编辑2:
OP连续提到一包10位数字
wrap = 0
newLine = True
with open('list.txt', encoding='utf-8') as file:
content = file.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
for line in content:
if wrap < 10:
print("{}, " .format(line), end = '')
else:
if newLine:
print("\n")
newLine = not newLine
print("{}, ".format(line), end='')
wrap += 1
输出:
one, two, three, four, five, six, seven, eight, nine, ten,
eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen,
答案 1 :(得分:0)
这可能完成了打印名称的工作:
with open('drop_words.txt', encoding='utf-8') as f:
words = [line for line.strip() in f]
print(','.join(words))
如果您想用7个单词来包装它们,可以使用以下函数:
def grouped(iterable, n):
return zip(*[iter(iterable)]*n)
>>> grouped(word, 7)