2016-09-24 54 views
-3

我正在尝试使用以下格式"a b c d e f g h"来读取文本文件。我拿一个新的空单word = []我如何获取列表而不是列表?

我的代码是:

f = open("letters.txt") 

word = [] 

for line in f: 
    line = line.split(" ") 
    word.append(line) 
print(word) 

但是,它给了我这样的目录列表:

[['a', 'b', 'c', 'd', 'e', 'f']] 

但我想要得到它在单一列表呢?

如:

['a', 'b', 'c'] 
+1

@RahulKP ^没有,只有第一行的字。 –

+0

你可能想澄清你的问题中有些令人困惑的术语。 '['a','b','c']'表明你想要一个字符列表,而我确定你想要一个*字词列表*。另外* word *(而不是word ** s **)作为列表出于同样的原因混淆。 –

+0

嗨PRnoob,请澄清^。问题现在还不清楚。 –

回答

0

尝试这样,

word = open("letters.txt").read().split() 

结果

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 
+0

对大文件不太好:) –

+0

@JacobVlijm OP介绍了关于小内容。这就是为什么我建议这个解决方案。 –

+0

他提到*格式*,我没有看到任何大小。在较小的文件上,我会尽自己的努力。我相信他的意思是除了他所描述的格式之外的其他东西...... –

0

您可以打印您的线路来代替。

f = open("letters.txt") 

for line in f: 
    line = line.split(" ") 
print line 
0

@ Rahul的回答是正确的。但是,这应该有助于您了解何时不使用append

append(x)将x添加为列表末尾的新元素。不要紧,什么x是extend会工作。

>>> l = [] 
>>> l.append(1) 
>>> l.append('a') 
>>> l.append({1,2,3}) 
>>> l.append([1,2,3]) 
>>> l 
[1, 'a', set([1, 2, 3]), [1, 2, 3]] 
>>> 
>>> 
>>> l = [] 
>>> l.extend(1) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'int' object is not iterable 
>>> l.extend([1]) 
>>> l.extend([4,5,6]) 
>>> l 
[1, 4, 5, 6] 
0

您应该知道每行代码中每个变量的数据是什么。如果你不知道 - 打印它,然后你就会知道。

,我会为你做这一次;)

f = open("letters.txt") 
# f is an open file object. BTW, you never close it. 
# Consider: with open("letters.txt", "rt") as f: 

word = [] 
# 'word' is a list. That is strange, why not 'words = []'? 

for line in f: 
    # 'line' is a string. Fine. 

    line = line.split(" ") 

    # 'line' is no longer a string. Not fine. 
    # This is perfectly valid code, but bad practice. 
    # Don't change the type of data stored in a variable, 
    # or you'll run into problems understanding what your code does. 
    # Make a new variable, if you need one, e.g. 'line_words'. 

    # Anyway, 'line' is now a list of words. Whatever. 

    word.append(line) 

    # This added a list (line) into another list (word). 
    # Now it is a list of lists. There is your error. 
    # 'word += line' would do what you wanted. 

一起:

with open("letters.txt", "rt") as f: 
    words = [] 
    for line in f: 
     words += line.split() 
0

你可以让你的当前结果后,尝试这样的:

import itertools 
a = [["a","b"], ["c"]] 
print list(itertools.chain.from_iterable(a)) 
0

split返回列表

使用sep作为分隔符字符串,返回字符串中单词的列表。

该列表所附截至word结束整个。这就是为什么你如果你想添加的,而不是追加的整个列表列表中的每个元素,得到名单

word [ 
    [ result of split of first line ] 
    [ result of split of second line ] 
    [ result of split of third line ] 
    [ ... ] 
] 

的列表,你可以使用extend,即

for line in f: 
    a = line.split(" ") 
    word.extend(a) 

虽然你可能想读多行

a = line.rstrip().split(" ") 

或只使用None如文字分隔符时rstrip,剥去尾随换行符

如果未指定九月或无,应用不同的分割算法:将连续空白的运行视为单个分隔符,并且结果在开始或结束时不包含空字符串if该字符串具有前导或尾随空白。因此,将空字符串或只包含空格的字符串拆分为无分隔符将返回[]。

a = line.split()