2017-12-14 3 views
3

rea과 같이 뒤죽박죽 된 단어가 포함 된 단어에서 올바른 영어 단어를 생성하려고 시도하는 경우 era, ear, are으로 배열 할 수 있으며 모든 가능한 순열 중에서 유효합니다. 나는이 시도했다 : 여기.txt 파일에서 목록의 요소를 검색하는 방법은 무엇입니까?

from itertools import permutations 
usr_input = input('your word:') 
permuted_list = [''.join(p) for p in permutations(usr_input)] #list of 
all possible permutation of user entered word 
count=0 
for word in permuted_list: 
    if word in open('wordlist.txt').read(): 
     print(word) 
     count+=1 

print(count) 

wordlist.txt 소스에서 설정 유효한 영어 단어 데이터입니다 : SCOWL here가.

그리고 친구들 내 문제는 올바른 순열 대신 모든 순열을 표시한다는 것입니다.

답변

2

다음은 파이썬에서 readlines()을 사용하여 문제를 해결하는 방법입니다.

from itertools import permutations 
usr_input = input("word: ?? ") 
permuted_list = [''.join(p) for p in permutations(str(usr_input))] 
count = 0 
for elem in permuted_list: 
    f = open("wordlist.txt") 
    for line in f.readlines(): 
     if elem == line.strip("\n"): 
      print (elem) 
      count += 1 

print (count) 

readlines() 기능은 \n로 읽어 때문에 파일에서 읽은 모든 라인은 각 문자열의 끝에서 \n을 가지고 있으며, strip()를 사용하지 않는 경우에 따라서 비교가 실패합니다. strip() 기능을 사용하면 \n을 (를) 벗겨 낼 수 있습니다.

관련 문제