2017-05-05 1 views
0

단어 생성기를 사용하여 단어 생성기를 만들고 각 항목을 파일에 쓰려고하는데, 파일 출력시 파일에 쓸 때 나는yield를 가진 단어 생성기 만들기

  C sh t d t d t d d � d d � �< } x2 t | j � � | k r] | j t t � � � q, WWd QXd S( Ns bfDict-t 
    use_stringt lengthi 
    s .txts a+( t openR t Truet lent  readlinest writet nextR ( t  max_wordst lib( ( s[ C:\Users\z-perkins-thomas\Documents\bin\python\HashKing\lib\attacks\bruteforce\bf_attack.pyt create_wordlist s )(
    t ost stringt randomR t lib.algorithms.hashing_algst lib.settingsR t FalseR R ( ( ( s[ C:\Users\z-perkins-thomas\Documents\bin\python\HashKing\lib\attacks\bruteforce\bf_attack.pyt <module> s 
l2\colorlog\colorlog\logging.pyt wrapper s  
( t  functoolst wraps( R R ( ( R sT c:\users\z-perk~1\appdata\local\temp\1\pip-build-rtaul2\colorlog\colorlog\logging.pyt ensure_configured s ( t __doc__t 
    __future__R R R t colorlog.colorlogR R R R R t  getLoggert debugt infot warningt errort criticalt logt  exceptiont 
    StreamHandler( ( ( sT c:\users\z-perk~1\appdata\local\temp\1\pip-build-rtaul2\colorlog\colorlog\logging.pyt <module> s"   
      s" C:\Python27\lib\ctypes\wintypes.pyR g s   t _COORDc   B s e Z d e f d e f g Z RS( t Xt Y( R R  R R ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyR n s  t POINTc   B s e Z d e f d e f g Z RS( t xt y( R R  R R ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyR r s  t SIZEc   B s e Z d e f d e f g Z RS( t cxt cy( R R  R R ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyR w s  c   C s | | d >| d >S( Ni i ( ( t redt greent blue( ( s" C:\Python27\lib\ctypes\wintypes.pyt RGB| s t FILETIMEc   B s e Z d e f d e f g Z RS( t 
    dwLowDateTimet dwHighDateTime( R R t DWORDR ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyR%  s  t MSGc   B sD e Z d e f d e f d e f d e f d e f d e f g Z RS( t hWndt messaget wParamt lParamt timet pt( R R  t HWNDt c_uintt WPARAMt LPARAMR( R R ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyR) � s      i t WIN32_FIND_DATAAc   B sp e Z d e f d e f d e f d e f d e f d e f d e f d e f d e e f d e d 
f g 
Z RS( t dwFileAttributest ftCreationTimet ftLastAccessTimet ftLastWriteTimet 
    nFileSizeHight nFileSizeLowt dwReserved0t dwReserved1t cFileNamet cAlternateFileNamei ( R R R( R% t c_chart MAX_PATHR ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyR4 � s         
t WIN32_FIND_DATAWc   B sp e Z d e f d e f d e f d e f d e f d e f d e f d e f d e e f d  e d 
f g 
Z RS( R5 R6 R7 R8 R9 R: R; R< R= R> i ( R R  R( R% t [email protected] R ( ( ( s" C:\Python27\lib\ctypes\wintypes.pyRA � s         
t ATOMt BOOLt BOOLEANt BYTEt CO 

내 생성은 다음과 같습니다

import itertools 

def word_generator(length_min=6, length_max=12, perms=False): 
    chrs = 'abc' 
    for n in range(length_min, length_max + 1): 
     for xs in itertools.product(chrs, repeat=n): 
      yield ''.join(xs) 


def create_wordlist(max_words=100000): 
    with open("words.txt", "a+") as lib: 
     while len(lib.readlines()) <= max_words: 
       lib.write(next(word_generator())) 

는이 파일에 이상한 출력의 원인은 무엇입니까?

텍스트 편집기 나 쉘의 인코딩이 ASCII 인코딩과 호환의 인코딩으로 설정 될 수있다 :

답변

0
내가하는 문제를 추측 할 수

, 그러나 여기 당신의 코드에서이 가능성이다.

텍스트 편집기로 파일을 여는 경우 텍스트 편집기의 인코딩을 확인해야합니다. 또는 쉘에서 파일을 읽은 경우 사용중인 쉘의 인코딩을 확인하십시오.

Python 2.X를 사용하고 시스템의 기본 인코딩을 변경하지 않은 경우 문자열이 파일로 ASCII로 기록됩니다. 3.X에서는 약간 다릅니다. open의 경우 인코딩을 명시 적으로 지정할 수 있습니다 : open('...', '+a', encoding='utf-8'). 따라서 3.x의 파일 인코딩을 open에 지정하고 3.X를 사용하는 경우 어떻게되는지보십시오.

0

먼저 코드를 실행하면 게시 한 것과 아무 것도 없습니다. 이 프로그램은 'words.txt'파일에 'a'문자를 넣는 무한 루프로 들어갔다. 내가 게시 한 이상한 문자열의 원인을 알 수는 없지만 코드에 3 가지 문제가있을 수 있습니다.

word_generator이 괜찮은 것 같습니다. 문제는 create_wordlist에 있습니다.

문제 1 : 코드 next(word_generator()) 대신 기존 시퀀스의 다음 요소를 가져 오는 이 파이스는 새로운 시퀀스를 생성 한 후 다음 요소의 소요됩니다. Sice는 새로운 시퀀스이며, 다음 요소는 첫 번째 요소 인 'aaaaaa'입니다. 반복 할 때마다 새 sequance를 만드는 것이므로 한 번만 생성하고 next을 반복해서 호출해야합니다. 예는 다음과 같습니다 :

wgen = word_generator() 
wilhe some_condition: 
    lib.write(next(wgen)) 

문제를 2 : 당신이 lib.readlines()의 크기에 따라 단어를 계산하려고하기 때문에, 당신이 파일이 한 줄에 하나의 단어를 기대하지만, 그 라인 lib.write(next(word_generator()))없는 생각 않습니다. '\ n'문자는 쓰이지 않습니다. 당신은 코드에 라인 lib.write('\n')을 추가하거나 한 줄에 하나의 단어하려면 단어에 '\ n'을 문자를 추가해야합니다

wgen = word_generator() 
wilhe some_condition: 
    lib.write(next(wgen) + '\n') 

문제 3 : 는 "words.txt을"열기 "a +"모드에서 스트림 위치는 파일의 끝으로 설정되고 이후에이 동작을 유지하는 lib.write()을 호출합니다. 그 때문에, lib.readlines()를 호출하면 (자), 파일의 말미로부터 행이 읽어 내 져 항상 사이즈가 0의 하늘의 배열이 돌려 주어집니다. 이로 인해 while len(lib.readlines()) <= max_words:은 무한 루프가됩니다.

하는 것은 문제를 해결하려면, 당신은 파일의 단어를 계산하는 또 다른 방법을 찾거나 파일마다의 모든 행을 읽기 때문에 lib.readlines() (See doc on seek)

를 호출하기 전에 파일의 시작 여행을 lib.seek(0, 0)를 사용해야 하나 반복은 몹시 비효율적이며, 나는 아래의 솔루션에서 또 다른 접근법을 취했다. 첫 번째 줄의 수를 한 번만 계산했습니다 :

def create_wordlist(max_words=100000): 
    with open("words.txt", "a+") as lib: 
     wgen = word_generator() # Creates the sequence of words 

     lib.seek(0, 0) # Goes to the begining of the file 
     line_count = len(lib.readlines()) # Counts how many lines the file has 

     # lib.readlines() set the stream position to the end, 
     # so now following 'lib.write()' calls will write to the end as expected. 

     # For each missing line before reaching 'max_words' lines 
     for i in range(line_count, max_words): 
      lib.write(next(wgen) + '\n') # Writes the next word in the sequence