2013-10-04 2 views
1

나는 한 줄에 200 단어를 포함하는 파일이 있습니다. 다른 모든 파일에서이 모든 단어를 검색하고 싶습니다. 나는이 단어들 중 하나를 포함하고있는 각 문장이 인쇄되기를 바란다. 지금은 첫 단어와 일치하는 단어 만 나타납니다. 그 후에는 멈 춥니 다.다른 문서에서 문자열을 포함하는 모든 문장 검색

corpus = open('C:\\Users\\Lucas\\Desktop\\HAIT\\Scriptie\\Tweet-corpus\\Corpus.txt', 'r', encoding='utf8') 

with open('C:\\Users\\Lucas\\Desktop\\HAIT\\Scriptie\\Tweet-corpus\\MostCommon3.txt', 'r', encoding='utf8') as list: 
for line in list: 
    for a in corpus: 
     if line in a: 
      print(a) 
+1

참고로, 당신은 당신의 코드에서 변수로, list''처럼, 빌트인 기능을 다시 사용하지 않아야합니다. – Moshe

+1

'corpus'는 파일 객체입니다. 외부 루프를 처음으로 통과 할 때, 내부의 for a corpus : 루프는 전체 파일을 읽습니다. 외부 루프의 모든 후속 반복에서 'corpus'는 여전히 파일 끝 부분에 있으므로 내부 루프는 절대로 본문에 들어 가지 않습니다. 그래서 첫 번째 줄만 일치 할 가능성이 있습니다. 예를 들어,'corpus'를 행 목록 ('.readlines()')으로 읽어 들일 수 있으며 대신에 그리스트를 반복 할 수 있습니다. –

답변

2
# Prepare the list of words 
word_file = open('wordfile', 'r', encoding='utf8') 
words = [word.strip() for word in word_file.readlines()] 
word_file.close() 

# Now examine each sentence: 
with open('sentencefile') as sentences: 
    for sentence in sentences: 
     found = False 
     for word in words: 
      if word in sentence: 
       found = True 
       break 
     if found: 
      print sentence 
관련 문제