Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_File_Import_Choice - Fatal编程技术网

如何导入列表?(python)

如何导入列表?(python),python,list,file,import,choice,Python,List,File,Import,Choice,我是Python新手……(我正在学习一周左右) 我正试图将一个文件作为列表导入,然后我想从中随机选择一个单词,以便在循环中使用它。?我不知道怎么做!提前感谢以下是概括的答案: f = open("path/to/file", "r") # opens the file as read-only content = f.read() # there are easier ways to do this, but.... ### do whatever you're doing here.... f

我是Python新手……(我正在学习一周左右)
我正试图将一个文件作为列表导入,然后我想从中随机选择一个单词,以便在循环中使用它。?我不知道怎么做!提前感谢

以下是概括的答案:

f = open("path/to/file", "r") # opens the file as read-only
content = f.read() # there are easier ways to do this, but....
### do whatever you're doing here....
f.close() # MAKE SURE YOU CLOSE FILES when you're done with them
# if you don't, you're asking for memory leaks.
您也可以使用上下文管理器,但阅读起来有点困难:

with open("path/to/file","r") as f:
    content = f.read() # again, this is not the BEST way....
    ### do stuff with your file
# it closes automatically, no need to call f.close()
在文件操作之外,下面是字符串->列表内容:

"a,b,c,d,e,f,g".split(',')
-> ['a','b','c','d','e','f','g']
# str.split creates a list from a string, splitting elements on
# whatever character you pass it.
这是随机的。选择:

import random

random.choice(['a','b','c','d','e','f','g'])
-> 'c' # chosen by fair dice roll, guaranteed to be random! ;)
# random.choice returns a random element from the list you pass it

我将给您举一个例子,其中包括一些最佳实践:

my_list = [] 
使用上下文管理器(
)打开文件(如果您有错误,它会自动关闭文件,与此处显示的其他方式相反),并使用通用读线(
rU
),启用标志(
r
是默认设置)

str.split()。如果你真的需要单词,可以使用自然语言工具包,这将帮助你更好地保留意思

您可以使用

my_list = file.read().split()
这可能适用于较小的文件,但请记住,如果这样做,在处理较大的文件时会遇到困难

使用“随机”模块选择单词(但在大多数情况下,将导入内容保留在脚本顶部):


我很高兴你选择了正确的标签,因为你明显缺乏关于这个主题的知识。你不能
导入
文件,但你可以
打开它!你的文件是什么样子的?你说的“从中随机选择一个单词,在循环中使用它”是什么意思?一旦你遇到了一个特定的问题,包括你尝试过的代码,以及它的输出如何与你期望的不匹配,你会立即报告。尝试搜索“打开文件python”“python随机选择列表”,等等,一个.txt文件…我必须为大学作业创建一个刽子手游戏。
my_list = file.read().split()
import random

my_random_word = random.choice(my_list)