简体   繁体   English

从文本文件创建列表

[英]Creating lists from text file

I want to create lists, but have the name of the lists in an external file called "mydog.txt". 我想创建列表,但是在名为“ mydog.txt”的外部文件中具有列表名称

mydog.txt : mydog.txt

bingo
bango
smelly
wongo

Here is my code that converts the text into list elements. 这是将文本转换为列表元素的代码。 I think it works but for some reason, the values are not saved after it's finished: 我认为它可以正常工作,但是由于某种原因,完成后并不能保存这些值:

def createlist(nameoflist):
    nameoflist = ["test"]
    print(nameoflist)

file = open("mydog.txt")
for i in file.readlines():
    i= i.replace("\n", "")
    print(i) #making sure text is ready to be created into a list name
    createlist(i)
file.close()
print("FOR fuction complete")

print(bingo) # I try to print this but it does not exist, yet it has been printed in the function

The subroutine is supposed to take a name (let's say "bingo") and then turn it into a list and have "test" inside of that list. 该子例程应该使用一个名称(例如“ bingo”),然后将其转换为一个列表,并在该列表中进行"test"

The final variables i should have are "bingo = ["test"], bango = ["test"], smelly = ["test"], wongo = ["test"] 我应该拥有的最终变量是“宾果= [“测试”],邦戈= [“测试”],有臭味的= [“测试”],馄饨= [“测试”]

The final thing that should be printed is ['test'] but the list does not exist. 最后要打印的内容是['test']但该列表不存在。

Why does it print out as a list when inside of the subroutine createlist but not outside the subroutine? 为什么在子例程createlist内部而不是子例程的外部将其打印为列表?

file = open("mydog.txt")
my_list =file.read().splitlines() # will create the list from the file which should contain only names without '\n'
file.close()

Or with block to not worry about file closing 或者with块不用担心文件关闭

with open("mydog.txt") as file:
    my_list =file.read().splitlines() # will create the list from the file which should contain only names without '\n'

In case you want to create the lists named after the names present in the text files you really should be creating a dict with keys as the names and value as list containing string test 如果要创建以文本文件中存在的名称命名的列表,则实际上应该创建一个dict ,其键为名称,值为包含字符串test列表

my_dict={i:['test'] for i in my_list}

Then try to print 然后尝试打印

print(my_dict['bingo']) # will print list ['test']

Printing entire dict 打印整个字典

print(my_dict) 

Output: 输出:

{'bango': ['test'], 'bingo': ['test'], 'smelly': ['test'], 'wongo': ['test']}
  1. You are adding variables to the local namespace of the function. 您正在将变量添加到函数的本地名称空间。 Nothing you add like that will be visible outside the function. 您添加的所有内容在函数外部均不可见。
  2. The assignment you are making is to a variable named by nameoflist , not the string that it refers to. 您要进行的分配是给一个以nameoflist命名的变量,而不是它所引用的字符串。

To get around that, you have to assign to the module namespace. 为了解决这个问题,您必须分配给模块名称空间。 This is actually not that difficult: 这实际上并不难:

def createlist(nameoflist):
    globals()[nameoflist] = ["test"]

The question you have to ask yourself is why you want to do that. 您必须问自己的问题是为什么要这么做。 Let's say you load your file: 假设您加载了文件:

with open("mydog.txt") as f:
    for line in f:
        createlist(line.strip())

Now indeed you can do 现在确实可以

>>> print(bingo)
['test']

However, the whole point of using a file is to have dynamic names. 但是,使用文件的重点是具有动态名称。 You don't know what names you will get up front, and once you stick them into the global namespace, you won't know which variables came from the file and which ones from elsewhere. 您不知道会用什么名字,一旦将它们放在全局名称空间中,就不会知道哪些变量来自文件,哪些变量来自其他地方。

Keep in mind that the global namespace is just a fancy but regular dictionary. 请记住,全局名称空间只是一个花哨的但常规的字典。 My recommendation is to hold the variables in your own dictionary, just for the purpose instead: 我的建议是将变量保存在自己的字典中,仅用于此目的:

with open("mydog.txt") as f:
    mylists = {line.strip(): ['test'] for line in f}

Now you can access the items by name: 现在,您可以按名称访问项目:

>>> mylists['bingo']
['test']

But more importantly, you can check what names you got and actually manipulate them in a meaningful way: 但更重要的是,您可以检查获得的名称并以有意义的方式实际操作它们:

>>> list(mylists.keys())
['bingo', 'bango', 'smelly', 'wongo']

You may use exec : 您可以使用exec

with open('mydog.txt') as f:
    list_names = [line.strip() for line in f]

for name in list_names:
    exec('{} = ["test"]'.format(name))

local = locals()
for name in list_names:
    print ('list_name:', name, ', value:', local[name])

or 要么

print (bingo, bango, smelly, wongo)

output: 输出:

list_name: bingo , value: ['test']
list_name: bango , value: ['test']
list_name: smelly , value: ['test']
list_name: wongo , value: ['test']

or 

['test'] ['test'] ['test'] ['test']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM