2016-09-03 2 views
-1

많은 단어 (각 줄마다 하나의 단어)가 포함 된 텍스트 파일이 있습니다. 각 단어를 읽고 단어를 수정 한 다음 수정 된 단어가 파일의 단어와 일치하는지 확인해야합니다. 내가 마지막 부분에 문제가있다 (그것은 내 코드에서 hasMatch 메서드이다). 그것은 아주 간단하게 들리며 무엇을해야하는지 알지만, 시도하는 것은 효과가 없습니다. 여기텍스트 파일의 특정 문자열 일치 문자열이 있습니까

#read in textfile 
myFile = open('good_words.txt') 


#function to remove first and last character in string, and reverse string 
def modifyString(str): 
    rmFirstLast = str[1:len(str)-2] #slicing first and last char 
    reverseStr = rmFirstLast[::-1] #reverse string 
    return reverseStr 

#go through list of words to determine if any string match modified string 
def hasMatch(modifiedStr): 
    for line in myFile: 
     if line == modifiedStr: 
      print(modifiedStr + " found") 
     else: 
      print(modifiedStr + "not found") 

for line in myFile: 
    word = str(line) #save string in line to a variable 

    #only modify strings that are greater than length 3 
    if len(word) >= 4: 
     #global modifiedStr #make variable global 
     modifiedStr = modifyString(word) #do string modification 
     hasMatch(modifiedStr) 

myFile.close() 
+0

파일 객체가 그 외부'for' 루프에 의해 소비되고 : 해당

rmFirstLast = str[1:len(str)-2] 

변경합니다. 'hasMatch'의 내부 루프는 당신이 생각하는대로하지 않을 것입니다. –

+0

그리고'word = str (line)'은 필요 없습니다. 'line'은 이미 문자열입니다 –

답변

2

몇 가지 문제

  1. 당신이 라인을 제거해야하거나 경기를 실패 라인 피드/CR의 문자를 얻을
  2. 한 번 전부 또는 파일 반복자의 파일을 읽을 필요 처음
  3. 속도가 나쁜 후에 실행이 : 대신 list
  4. 슬라이싱가 지나치게 복잡
  5. 그름의 set를 사용하여 검색 질주 : str[1:-1] (내 답변을 주석 사람들 덕분에)
  6. 전체 코드는 정말 복잡합니다 & 복잡합니다. 나는 그것을 몇 줄에 걸쳐 요약했다.

코드 :

so found (was most) 
or found (was from) 
no found (was long) 
on found (was know) 
to found (was both) 

편집 : 다음 set을 삭제하고 bisect를 사용하는 다른 버전 나는 일반적인 영어 단어의 목록에서 프로그램을 테스트하고 내가 그 경기를 가지고

#read in textfile 
myFile = open('good_words.txt') 
# make a set (faster search), remove linefeeds 
lines = set(x.strip() for x in myFile) 
myFile.close() 

# iterate on the lines 
for word in lines: 
    #only consider strings that are greater than length 3 
    if len(word) >= 4: 
     modifiedStr = word[1:-1][::-1] #do string modification 
     if modifiedStr in lines: 
      print(modifiedStr + " found (was "+word+")") 
     else: 
      print(modifiedStr + " not found") 

해시/해시 충돌을 피하기 위해 정렬 된 목록에 추가하십시오.

import os,bisect 

#read in textfile 
myFile = open("good_words.txt")) 
lines = sorted(x.strip() for x in myFile) # make a sorted list, remove linefeeds 
myFile.close() 

result=[] 
for word in lines: 

    #only modify strings that are greater than length 3 
    if len(word) >= 4: 
     modifiedStr = word[1:-1][::-1] #do string modification 
     # search where to insert the modified word 
     i=bisect.bisect_left(lines,modifiedStr) 
     # if can be inserted and word is actually at this position: found 
     if i<len(lines) and lines[i]==modifiedStr: 
      print(modifiedStr + " found (was "+word+")") 
     else: 
      print(modifiedStr + " not found") 
+0

좋은 답변입니다 또한'rmFirstLast = str [1 : len (str) -2]'는'str [1 : len (str) -1]이어야합니다' –

+0

'strip (x)'. 당신은'x.strip()'을 의미했습니다. –

+1

@TrevorMerrifield'len'은 그곳에있을 필요조차하지 않습니다 ... –

0

코드에서 첫 번째와 마지막 문자가 아니라 첫 번째와 마지막 두 개의 문자 만 잘라냅니다.

rmFirstLast = str[1:len(str)-1] 
+0

이 아닌 2 차항이되지만 다른 많은 문제가 있습니다. –

+0

예, 눈치 채지 못했습니다. – Kandhan

+0

예, 이것을 지적 해 주셔서 감사합니다. 마지막으로 두 글자를 잘라 내기 위해 -1을 (-2 대신) 테스트했기 때문에 슬라이스를 설정했습니다. 작동하지 않습니다 ... 아마도 빈 숯은 그걸 가지고 뭔가 관련이 있습니다. –

관련 문제