2014-11-26 4 views
0

저는 파이썬 프로그래밍에 익숙하지 않습니다. 지금은 텍스트 파일에서 자연어 처리를하고 있습니다. 문제는 제가 약 200 개의 텍스트 파일을 가지고있어서 각 파일을 개별적으로로드하고 동일한 방법을 적용하기가 매우 어렵다는 것입니다.파이썬을 사용하여 여러 텍스트 파일에 동일한 알고리즘을로드하고 적용하는 방법

import nltk 
from nltk.collocations import * 
from nltk.tokenize import word_tokenize 
from nltk.corpus import stopwords 
from nltk import FreqDist 
with open("c:/users/user/desktop/datascience/sotu/stopwords.txt", 'r') as sww: 
    sw = sww.read() 
**with open("c:/users/user/desktop/datascience/sotu/a41.txt", 'r') as a411: 
    a41 = a411.read() 
    a41c=word_tokenize(str(a41)) 
    a41c = [w for w in a41c if not w in sw]** 

그래서 내가 여러 파일에이 방법을 적용 할 :

여기 내 프로그램입니다. 한 단계에서 모든 파일을로드하고 동일한 방법을 적용 할 수있는 방법이 있습니까? 나는 이것을 시도했지만 작동하지 않았다 :

import os 
import glob 
import nltk 
from nltk.collocations import * 
from nltk.tokenize import word_tokenize 
from nltk.corpus import stopwords 
from nltk import FreqDist 
with open("c:/users/user/desktop/datascience/sotu/stopwords.txt", 'r') as sww: 
    sw = sww.read() 
for filename in glob.glob(os.path.join("c:/users/user/desktop/DataScience/sotu/",'*.txt')): 
    filename=word_tokenize(str(filename)) 
    filename = [w for w in filename if not w in sw] 
xqc=FreqDist(filename) 

이 도움을 주시기 바랍니다.

+0

"...하지만 작동하지 않습니까?" 어떤 오류 또는 무엇인가? 'filenamec'이란 무엇입니까? – Marcin

+0

아무 일도 없었어요. 그리고 내가 파일 이름을 인쇄했을 때 ... 'filename'이 정의되어 있지 않습니다. – Learner27

+0

무엇이'filenamec'입니까? 또한 파일의 확장자는'* .text'이거나 첫번째 예제에서와 같은'* .txt'입니까? – Marcin

답변

2

두 번째 방법은 실제로 검사 할 파일을로드하지 않기 때문에 작동하지 않습니다. 첫 번째 (아마도 작동중인 예)에서는 파일의 내용을 나타내는 문자열에 대해 word_tokenize를 호출하고 두 번째에는 파일 이름에 대해 수행하고 있습니다. 코드가 여기 정말 불분명하다, 참고 :

for filename in glob.glob(os.path.join("c:/users/user/desktop/DataScience/sotu/",'*.txt')): filename=word_tokenize(str(filename)) filename = [w for w in filename if not w in sw]

3 개 라인에서 파일 이름을 3 번을 사용하지 마십시오! 첫 번째 사용은 표현 된 것만 사용하고 두 번째는 토큰 화 된 단어 목록을 나타내며 세 번째 단어는 동일한 단어 목록을 나타내지 만 필터링됩니다.

또 다른 힌트로, 변수에보다 설명적인 이름을 붙이십시오. 나는 NLP에 익숙하지 않지만 코드를 통해 누군가는 xqc가 무엇을 의미하는지 알고 싶어 할 것입니다.

다음은 코드 작성 방법을 추론 할 수있는 간단한 코드입니다.

stopwords_filename = "words.txt" 
stop_words = [] 
with open(stopwords_filename, "r") as stopwords_file: 
    stop_words = stopwords_file.read() 

words_input_dir = "c:/users/user/desktop/DataScience/sotu/" 

for filename in os.listdir(words_input_dir): 
    if filename.endswith(".txt"): 
     with open(filename, "r") as input_file: 
      input_tokens = word_tokensize(input_file.read()) 
      # Do everything else.` 
+0

감사합니다. 도움 :) – Learner27

관련 문제