2016-09-24 42 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() 
相關問題