我试图创建识别任务。我有一个.txt文件,里面有600个单词。从这个列表中,我试图创建子列表(例如List1,List2。)由于某种原因,我无法从子列表中获取单词列表。它只返回[]。请帮忙!!
wordNum = 0
# Create list
wordList = []
with open('mfwords.txt','r') as f:
for line in f:
wordNum = wordNum+1
for word in line.split():
wordList.append(word)
# Shuffle list
import random
random.shuffle(wordList)
# Number of words in list
listLen = 50
# List 1 is first 50 words of wordList
list1 = wordList[0:50]
# List 2 is first 100 words of wordList
list2 = wordList[0:100]
答案 0 :(得分:3)
您的with open
区块对我来说并不合适。第二个for
需要在第一个{,1}内,否则它只会在line
指向文件的最后一行时执行。尝试:
with open('mfwords.txt','r') as f:
for line in f:
for word in line.split():
wordList.append(word)