【问题标题】:Creating a word generator with yield使用 yield 创建单词生成器
【发布时间】:2017-10-04 04:51:14
【问题描述】:

我正在尝试使用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   c_wcharR@   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()))

是什么导致了这个文件中的奇怪输出?

【问题讨论】:

    标签: python python-2.7 generator yield


    【解决方案1】:

    我只能猜测问题,但从您的代码来看,可能性如下:

    您的文本编辑器或 shell 的编码可能设置为与 ASCII 编码不兼容的编码。

    如果您碰巧使用文本编辑器打开文件,则应检查文本编辑器的编码。或者,如果您碰巧在 shell 中读取文件,请检查您正在使用的 shell 的编码。

    如果您使用的是 Python 2.X 并且您没有更改系统中的默认编码,那么您的字符串将作为 ASCII 写入文件。在 3.X 中略有不同,对于open,您可以明确指定编码:open('...', '+a', encoding='utf-8')。所以尝试在open 中指定3.X 文件的编码,看看如果你使用3.X 会发生什么。

    【讨论】:

      【解决方案2】:

      首先,当我运行你的代码时,我得到的和你发布的一样。程序进入了将“a”字符放入“words.txt”文件的无限循环。我不知道是什么导致了您发布的奇怪字符串,但我可以在您的代码中看到 3 个问题。

      您的word_generator 似乎没问题。问题在create_wordlist

      问题 1: 这段代码next(word_generator()) 不是获取现有序列的下一个元素,而是创建一个新序列,然后将其作为下一个元素。因为它是一个全新的序列,它的下一个元素是它的第一个元素,在这种情况下是“aaaaaa”。 与其每次迭代都创建一个新序列,不如只创建一次,然后在其上重复调用next。示例如下:

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

      问题 2: 由于您尝试按lib.readlines() 的大小来计算单词,我相信您希望文件每行只有一个单词,但这不是lib.write(next(word_generator())) 的行,因为没有写入'\n' char。如果您希望每行一个单词,您应该将 lib.write('\n') 行添加到代码中,或者在单词后面附加一个 '\n' 字符:

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

      问题 3: 当您以“a+”模式打开“words.txt”时,流位置设置为文件末尾,随后对lib.write() 的调用保持此行为。因此,对lib.readlines() 的调用将从文件末尾开始读取行,因此总是返回一个大小为零的空数组。这使您的while len(lib.readlines()) &lt;= 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
      

      【讨论】:

        猜你喜欢
        • 2020-04-07
        • 2021-09-05
        • 2022-12-31
        • 1970-01-01
        • 2021-03-17
        • 1970-01-01
        • 2017-07-07
        • 2013-12-13
        • 2019-07-25
        相关资源
        最近更新 更多