2016-10-27 2 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()을 호출하면됩니다.

당신은 공백에 분할해야
[word.translate(None, string.punctuation).lower() for line in open(words_file) for word in line.split()] 

(기본값) 단어를 분리 :

0

여기 당신이 원하는 모든 것을해야 지능형리스트입니다. 그런 다음 각 결과 문자열을 변환하여 구두점을 제거하고 소문자로 만들 수 있습니다.

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()]