2012-11-06 4 views
7

私はtest.txtという名前のテキストファイルを持っています。私はそれを読んで、ファイルからすべての単語のリスト(改行を削除したもの)を返したいと思います。pythonでファイルを読み込んだ後に単語のリストを返す

これは私の現在のコードです:このコードを実行する

def read_words(test.txt): 
    open_file = open(words_file, 'r') 
    words_list =[] 
    contents = open_file.readlines() 
    for i in range(len(contents)): 
     words_list.append(contents[i].strip('\n')) 
    return words_list  
    open_file.close() 

は、このリストを生成します。

['hello there how is everything ', 'thank you all', 'again', 'thanks a lot'] 

私はリストには、次のようになりたい:

['hello','there','how','is','everything','thank','you','all','again','thanks','a','lot'] 
+1

http://docs.python.org/2/library/stdtypes.html#str分割 – kreativitea

答えて

13

words_list.append(...)を交換してください次のようなforループの行:

words_list.extend(contents[i].split()) 

これにより、空白文字の各行が分割され、結果のリストの各要素がwords_listに追加されます。

やリストの内包表記と関数全体を書き換えるための別の方法として:ここで

def read_words(words_file): 
    return [word for line in open(words_file, 'r') for word in line.split()] 
+0

ありがとうございましたF.J、それは有用であった –

5

が、私はそれを書きたい方法です:

def read_words(words_file): 
    with open(words_file, 'r') as f: 
    ret = [] 
    for line in f: 
     ret += line.split() 
    return ret 

print read_words('test.txt') 

機能が多少使って短縮することが可能itertoolsですが、私は個人的に結果をあまり読みにくくしています:

import itertools 

def read_words(words_file): 
    with open(words_file, 'r') as f: 
    return list(itertools.chain.from_iterable(line.split() for line in f)) 

print read_words('test.txt') 

2番目のバージョンの素晴らしい点は、完全にジェネレータベースにすることができ、ファイルのすべての単語を一度にメモリに保存しないことです。これを行うには、いくつかの方法があります

with open(file) as f: 
    words = f.read().split() 
17

ファイルのサイズによっては、これがそうです。

:あなたは、各単語が一度だけ出現する単語のリストを返したい場合は

def getWords(filepath): 
    with open('filepath') as f: 
     return list(itertools.chain(line.split() for line in f)) 

:あなたが繰り返し言葉気にしないのであれば

:ここではいくつかあります

注:これは言葉の順序を保持しません

def getWords(filepath): 
    with open('filepath') as f: 
     return {word for word in line.split() for line in f} # python2.7 
     return set((word for word in line.split() for line in f)) # python 2.6 

あなたがしたい場合セットは単語の順番保存しておきたい--and--:

def getWords(filepath): 
    with open('filepath') as f: 
     return collections.Counter(itertools.chain(line.split() for line in file)) 

が、これらは

を助けるホープ:あなたは単語の頻度辞書
をしたい場合は

def getWords(filepath): 
    with open('filepath') as f: 
     words = [] 
     pos = {} 
     position = itertools.count() 
     for line in f: 
      for word in line.split(): 
       if word not in pos: 
        pos[word] = position.next() 
         words.append(word) 
    return sorted(words, key=pos.__getitem__) 

+1

+1それは納得してポイントです。 –

関連する問題