【问题标题】:Naming lists based on the names of text files基于文本文件名称的命名列表
【发布时间】:2018-10-16 17:11:38
【问题描述】:

我正在尝试编写一个函数,该函数从文本文件中获取单词列表并将文件中的每个单词附加到一个列表中,并与文本文件同名。例如,使用文本文件Verbs.txtNouns.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 循环?

【问题讨论】:

  • 使用dict Luke。

标签: python python-3.x list file for-loop


【解决方案1】:

您应该使用dict 来表示类似(未经测试):

results = {}
for file in file_list:
    infile = open(file, 'r')
    word_type = file[:-4]
    results[word_type] = [line for line in infile]
return results

你也不需要列表理解,你可以这样做:

results[word_type] = list(infile)

【讨论】:

    【解决方案2】:

    您可以通过操作存储局部变量的locals() 字典来创建具有自定义名称的新变量。但很难想象在任何情况下这是一个好主意。我强烈推荐 Stephen Roach 的使用字典的建议,它可以让你更整齐地跟踪列表。但如果你真的想为每个文件创建局部变量,你可以对他的代码稍作改动:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 2016-04-30
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2020-12-03
      • 2021-07-13
      相关资源
      最近更新 更多