2017-12-14 11 views
3

reaのようなひどい文字を含む単語から有効な英語の単語を生成しようとしています。eraearareのように配置することができます。 私はこの試みている:SCOWL here:ここリストの要素を.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は、ソースから設定された有効英単語データです。

私の問題は、有効なものの代わりにすべての並べ替えを表示することです。

答えて

2

ここでは、readlines()をPythonで使用して問題を解決する方法を示します。

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を取り除くことができます

関連する問題