我正在尝试混合单词列表中的单词并创建新单词列表
这是我的词汇表
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)
答案 0 :(得分:0)
您基本上可以使用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]))
答案 1 :(得分:0)
带有下划线的您可以使用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))