我正在尝试混合单词列表中的单词并创建新的单词列表
这是我的单词表
Nice
have fun
its cool
_
make
quote
backtick
_
jobs
public
over
我想做的是混合这些单词,并希望输出像这样。
Nice
make
jobs
_
have fun
quote
public
_
its cool
backtick
over
这就是我尝试过的
with open('wordlist.txt') as f:
wordlist= f.read().splitlines()
newwordlist = []
for x in range(2):
newx = wordlist[x]
newwordlist.append(newx)
您基本上可以用zip
:"转置"它们
with open('wordlist.txt','r') as f:
wordlist= list(zip(*[i.splitlines() for i in f.read().split('_')]))
如果没有下划线:
with open('wordlist.txt','r') as f:
wordlist= list(zip(*[f.readlines()[i:i+3] for i in range(0,len(f.readlines()),3)]))
并创建新文件:
...
with open('wordlist2.txt','w') as f2:
f2.write('_'.join(['n'.join(i) for i in wordlist]))
使用下划线可以使用U9 Forward 提出的概念
with open('wordlist.txt','r') as f:
wordlist = list(zip(*[i.splitlines() for i in f.read().split('_n')]))
with open('newwordlist.txt','w') as f2:
f2.write('n_n'.join(['n'.join(i) for i in wordlist]))
U9真的很接近,只是换行成了问题
如果你只有一个单词列表,没有下划线,你可以使用random.shuffle
。
from random import shuffle
with open('wordlist.txt', 'r') as f:
words = f.read().splitlines()
shuffle(words) # shuffles words randomly
with open('newwordlist.txt', 'w') as f2:
f2.write('n'.join(words))