You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于文本文件名命名列表:编写循环加载词到同名列表的函数

Solution: Load Word Lists into Named Lists

Got it, let's tackle this problem. The goal is to read each word list file and store its contents in a list named after the file (without the .txt extension, using lowercase for consistency with Python's naming conventions). Here's a clean, robust implementation:

Using a dictionary to store all your word lists is the best practice—it avoids messy dynamic variable creation and makes it easy to manage and iterate over your word sets later.

def loadAllWords():
    # List of your word files (add/remove as needed)
    fileList = [
        'Adjectives.txt', 'Adverbs.txt', 'Conjunctions.txt',
        'IntransitiveVerbs.txt', 'Leadin.txt', 'Nounmarkers.txt',
        'Nouns.txt', 'Verbs.txt'
    ]
    
    # Dictionary to hold all word lists (key = list name, value = list of words)
    word_lists = {}
    
    for filename in fileList:
        # Convert filename to a valid list name: remove .txt, lowercase
        list_name = filename.replace('.txt', '').lower()
        
        # Read file with error handling to avoid crashes
        try:
            with open(filename, 'r', encoding='utf-8') as file:
                # Clean up words: strip whitespace, skip empty lines
                words = [line.strip() for line in file if line.strip()]
                word_lists[list_name] = words
        except FileNotFoundError:
            print(f"Warning: Couldn't find {filename} — skipping this file.")
        except Exception as e:
            print(f"Error reading {filename}: {str(e)}")
    
    return word_lists

Key Details:

  • Clean Word Processing: The list comprehension removes extra spaces/newlines and skips empty lines, so your lists won't have useless empty strings.
  • Error Handling: The try-except blocks prevent the entire function from failing if one file is missing or corrupted.
  • Scalability: Add more files to fileList without changing any other code—they'll automatically be added to the dictionary.

How to Use This

# Load all word lists into the dictionary
all_word_lists = loadAllWords()

# Access individual lists by name
print(all_word_lists['nouns'])  # Prints all words from Nouns.txt
print(all_word_lists['verbs'])  # Prints all words from Verbs.txt

# Iterate over all lists if needed
for list_name, words in all_word_lists.items():
    print(f"{list_name.capitalize()}: {words[:5]}...")  # Print first 5 words of each list

If you really need separate variables instead of a dictionary (e.g., for legacy code), you can dynamically create local variables. Note that this is less maintainable and can cause issues with unusual filenames:

def loadAllWords():
    fileList = [
        'Adjectives.txt', 'Adverbs.txt', 'Conjunctions.txt',
        'IntransitiveVerbs.txt', 'Leadin.txt', 'Nounmarkers.txt',
        'Nouns.txt', 'Verbs.txt'
    ]
    
    for filename in fileList:
        list_name = filename.replace('.txt', '').lower()
        try:
            with open(filename, 'r', encoding='utf-8') as file:
                words = [line.strip() for line in file if line.strip()]
                # Dynamically assign to a local variable
                locals()[list_name] = words
        except Exception as e:
            print(f"Problem with {filename}: {e}")
    
    # Return the variables you need (must match the file list)
    return adjectives, adverbs, conjunctions, intransitiveverbs, leadin, nounmarkers, nouns, verbs

Usage for Variable Version:

adj, adv, conj, iv, leadin, nm, nouns, verbs = loadAllWords()
print(nouns)  # Directly access the nouns list

内容的提问来源于stack exchange,提问作者Jim421616

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:43:54