Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于文本文件名称的命名列表_Python_Python 3.x_List_File_For Loop - Fatal编程技术网

Python 基于文本文件名称的命名列表

Python 基于文本文件名称的命名列表,python,python-3.x,list,file,for-loop,Python,Python 3.x,List,File,For Loop,我正在尝试编写一个函数,它从文本文件中获取单词列表,并将文件中的每个单词附加到一个列表中,使用与文本文件相同的名称。例如,使用文本文件Verbs.txt和nomes.txt将导致Verbs.txt中的所有单词位于Verbs列表中,所有名词位于nomes列表中。我尝试在for循环中执行此操作: def loadAllWords(): fileList = ['Adjectives.txt', 'Adverbs.txt', 'Conjunctions.txt',

我正在尝试编写一个函数,它从文本文件中获取单词列表,并将文件中的每个单词附加到一个列表中,使用与文本文件相同的名称。例如,使用文本文件
Verbs.txt
nomes.txt
将导致
Verbs.txt
中的所有单词位于
Verbs
列表中,所有名词位于
nomes
列表中。我尝试在
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循环?

您应该使用for,比如(未测试):

此外,您不需要理解列表,只需执行以下操作:

results[word_type] = list(infile)
您应该使用类似的(未经测试的):

此外,您不需要理解列表,只需执行以下操作:

results[word_type] = list(infile)

通过操作存储局部变量的
locals()
字典,可以创建具有自定义名称的新变量。但很难想象在任何情况下这都是一个好主意。我强烈推荐斯蒂芬·罗奇关于使用字典的建议,这会让你更准确地记录列表。但是,如果您真的想为每个文件创建局部变量,您可以在他的代码中使用一些细微的变化:

results = {}
for file in file_list:
    with open(file, 'r') as infile:
        word_type = file[:-4]
        results[word_type] = list(infile)
# store each list in a local variable with that name
locals.update(results)

通过操作存储局部变量的
locals()
字典,可以创建具有自定义名称的新变量。但很难想象在任何情况下这都是一个好主意。我强烈推荐斯蒂芬·罗奇关于使用字典的建议,这会让你更准确地记录列表。但是,如果您真的想为每个文件创建局部变量,您可以在他的代码中使用一些细微的变化:

results = {}
for file in file_list:
    with open(file, 'r') as infile:
        word_type = file[:-4]
        results[word_type] = list(infile)
# store each list in a local variable with that name
locals.update(results)
用卢克,用卢克。