2016-10-27 4 views
1

テキストファイルをインポートしてテキストを各単語の文字列リストに戻そうとしていますが、小文字と句読点も返しません。リスト内の複数の関数を呼び出す

次のコードを作成しましたが、これは各単語を文字列に分割しません。また、理解に.lower()を追加することは可能ですか?

def read_words(words_file): 
    """Turns file into a list of strings, lower case, and no punctuation""" 
    return [word for line in open(words_file, 'r') for word in line.split(string.punctuation)] 
+0

例の入力を追加してください、あなたが出力として取得したい、と実際の出力あなたが取得しているもの。 – CAB

+1

プロセスがリスト内包である必要があるのはなぜですか? – wwii

+0

これは理解する必要はありません。ちょうどそれが最小のコード量になると思った – John

答えて

0

はい、.lowerを理解に追加できます。おそらくwordにあるはずです。また、次のコードはstring.punctuationのために各単語を分割しない可能性があります。引数なしで.split()を呼び出す空白で分割しようとしているのであれば十分です。

0

は、ここであなたが望むすべてを行う必要があり、リストの内包表記です:

[word.translate(None, string.punctuation).lower() for line in open(words_file) for word in line.split()] 

あなたは言葉を区切るには空白(デフォルト)に分割する必要があります。結果の各文字列を変換して句読点を削除し、小文字にすることができます。

0

mapping to translate the wordsを使用して、ジェネレータ機能で使用してください。

import string 
def words(filepath): 
    '''Yield words from filepath with punctuation and whitespace removed.''' 

    # map uppercase to lowercase and punctuation/whitespace to an empty string 
    t = str.maketrans(string.ascii_uppercase, 
         string.ascii_lowercase, 
         string.punctuation + string.whitespace) 

    with open(filepath) as f: 
     for line in f: 
      for word in line.strip().split(): 
       word = word.translate(t) 
       # don't yield empty strings 
       if word: 
        yield word 

使用

for word in words('foo.txt'): 
    print(word) 
0
import string 
def read_words(words_file): 
    """Turns file into a list of strings, lower case, and no punctuation""" 
    with open(words_file, 'r') as f: 
     lowered_text = f.read().lower() 
    return ["".join(char for char in word if char not in string.punctuation) for word in lowered_text.split()] 
関連する問題