[英]Reading characters from file into list
I have a part of a program with the following code 我有以下代码的程序的一部分
file1 = [line.strip()for line in open(sometext.txt).readlines()]
print ((file1)[0])
and when the code is executed it gives me the whole contents of the txt file which is a very long sentence, how would I go about reading every letter and placing it in a list to index each character separately? 当执行代码时,它给了我txt文件的全部内容,这是一个很长的句子,我将如何阅读每个字母并将其放在列表中以分别索引每个字符? I have used the list() function which seems to put the whole text file into a list and not each character. 我使用过list()函数,该函数似乎将整个文本文件放入一个列表中,而不是每个字符中。
You can use file.read()
rather than file.readlines()
: 您可以使用file.read()
而不是file.readlines()
:
file1 = [char for char in open(sometext.txt).read()]
You don't really need list-comprehension, however; 但是,您实际上并不需要列表理解。 instead you can do this: 相反,您可以这样做:
file1 = list(open(sometext.txt).read())
Also, as @furas mentioned in his comment, you don't need a list to have indexing. 另外,正如@furas在他的评论中提到的那样,您不需要列表即可建立索引。 str
also has a method called index
, so you could say file1 = open(sometext.txt).read()
and still be able to use file1.index()
. str
还具有一种称为index
的方法,因此您可以说file1 = open(sometext.txt).read()
仍然可以使用file1.index()
。 Note, str
also has a find
method which will return -1 if the substring is not found, rather than raising a ValueError. 注意, str
还有一个find
方法,如果未找到子字符串,它将返回-1,而不是引发ValueError。
With a read()
is enough. 用read()
就足够了。 Plus. 加。 if you want to store the list without \\n
and white spaces, you can use: 如果要存储不带\\n
和空格的列表,则可以使用:
char_list = [ch for ch in open('test.txt').read() if ch != '\n' if ch != ' ']
You can remove the if
statements if you want to maintain them. 如果要维护if
语句,则可以删除它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.