我在将文本文件读入列表时遇到问题,目前我所拥有的是:
lines = open ('dracula.txt', 'r'). readlines ()
Run Code Online (Sandbox Code Playgroud)
其中dracula.txt是与程序在同一目录中的文本文件,但是在运行程序时,Python会出现:
No such file or directory: 'dracula.txt'
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它不会找到文本文件并将其读取到名为lines的列表中,是否有人有任何想法?
我只是想知道在Python的精彩世界中是否有任何方法可以从这样的事情:
dict1 = {'a': [1,2,3], 'b': [4,5,6]}
Run Code Online (Sandbox Code Playgroud)
至
dict2 = {'a':1, 'a':2, 'a':3,'b':4, 'b': 5, 'b': 6]
Run Code Online (Sandbox Code Playgroud)
或等价,顺序是无关紧要的,但我需要一些方法将dict1分解为一些东西,我可以将数值分配给新列表的索引,键作为这些索引的实际值,例如dict1将变为:
[0, a, a, a, b, b, b]
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,虽然越白痴证明答案越好.
我再次感激你了.
我正在编写一个程序来读取5个文件中的文本行,并将这5个文件中的文本编译成相应的列表.
但是我在使程序实际读取文本到列表时遇到了很多麻烦,这是我的代码到目前为止:
from random import random
from dice import choose
b = open ('E:\Videos, TV etc\Python\ca2\beginning.txt', 'r'). readlines ()
stripped_b = [item.strip() for item in b]
a = open ('E:\Videos, TV etc\Python\ca2\adjective.txt', 'r'). readlines ()
stripped_a = [item.strip() for item in a]
i = open ('E:\Videos, TV etc\Python\ca2\inflate.txt', 'r'). readlines ()
stripped_i = [item.strip() for item in i]
n = open ('E:\Videos, TV etc\Python\ca2\noun.txt', 'r'). readlines ()
stripped_n = [item.strip() for item in n]
phrase = []
turn = 0 …Run Code Online (Sandbox Code Playgroud) 我需要获取一个列表并使用字典来编目列表中特定项目的位置,例如:
L = ['a','b','c','b','c','a','e']
字典需要包含以下内容:
D = {'a':0,5,'b':1,3,'c':2,4,'e':6}
但是,如果我使用我写的:
for i in range(len(word_list)):
if D.has_key('word_list[i]') == False:
D['word_list[i]'] = i
else:
D[word_list[i]] += i
Run Code Online (Sandbox Code Playgroud)
然后我得到一个单词的KeyError,我不明白为什么我应该得到一个错误.