【发布时间】:2018-10-16 17:11:38
【问题描述】:
我正在尝试编写一个函数,该函数从文本文件中获取单词列表并将文件中的每个单词附加到一个列表中,并与文本文件同名。例如,使用文本文件Verbs.txt 和Nouns.txt 将导致Verbs.txt 中的所有单词都在verbs 列表中,而所有名词都在nouns 列表中。我正在尝试在for 循环中执行此操作:
def loadAllWords():
fileList = ['Adjectives.txt', 'Adverbs.txt', 'Conjunctions.txt',
'IntransitiveVerbs.txt', 'Leadin.txt', 'Nounmarkers.txt',
'Nouns.txt', 'TransitiveVerbs.txt']
for file in fileList:
infile = open(file, 'r')
word_type = file[:-4]
word_list = [line for line in infile]
return word_list
当然,我可以轻松地为每个文本文件执行一次:
def loadAllWords():
infile = open("Adjectives.txt", "r")
wordList = []
wordList = [word for word in infile]
return wordList
但我希望我的函数能够自动处理每个函数。有没有办法做到这一点,还是我应该为每个文件坚持一个 for 循环?
【问题讨论】:
-
使用
dictLuke。
标签: python python-3.x list file for-loop