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,