【问题标题】:Iterate through words of a file in Python在 Python 中遍历文件的单词
【发布时间】:2011-10-12 19:12:25
【问题描述】:

我需要遍历一个大文件的单词,该文件由一条长长的行组成。我知道逐行遍历文件的方法,但是由于其单行结构,它们不适用于我的情况。

还有其他选择吗?

【问题讨论】:

  • 使用缓冲区读取少量文件...my_file.read(200)

标签: python file io


【解决方案1】:

这真的取决于你对单词的定义。但是试试这个:

f = file("your-filename-here").read()
for word in f.split():
    # do something with word
    print word

这将使用空白字符作为单词边界。

当然,记得正确打开和关闭文件,这只是一个简单的例子。

【讨论】:

    【解决方案2】:

    长长的队伍?我认为这条线太大而无法合理地放入内存中,因此您需要某种缓冲。

    首先,这是一种不好的格式;如果您对文件有任何控制权,请使其每行一个字。

    如果没有,请使用类似:

    line = ''
    while True:
        word, space, line = line.partition(' ')
        if space:
            # A word was found
            yield word
        else:
            # A word was not found; read a chunk of data from file
            next_chunk = input_file.read(1000)
            if next_chunk:
                # Add the chunk to our line
                line = word + next_chunk
            else:
                # No more data; yield the last word and return
                yield word.rstrip('\n')
                return
    

    【讨论】:

    • 您应该记住,当您想在文件中每行写入一个单词时,此方法可以正常工作,但如果您只想使用它以便只产生一个单词,则不要使用.当我们在块中有dog\ncat 时,这个不起作用。它产生dog\ncat,而不是dog,然后是cat。当dog\ncat 被打印出来时,它看起来没问题,但这是虚幻的。
    【解决方案3】:

    有更有效的方法可以做到这一点,但从语法上讲,这可能是最短的:

     words = open('myfile').read().split()
    

    如果内存是一个问题,您不会想要这样做,因为它会将整个内容加载到内存中,而不是对其进行迭代。

    【讨论】:

      【解决方案4】:

      你真的应该考虑使用Generator

      def word_gen(file):
          for line in file:
              for word in line.split():
                  yield word
      
      with open('somefile') as f:
          word_gen(f)
      

      【讨论】:

        【解决方案5】:

        我已经回答了一个类似的问题before,但我已经改进了该答案中使用的方法,这里是更新版本(复制自最近的answer):

        这是我完全实用的方法,它避免了阅读和 分割线。它利用了itertools 模块:

        注意python 3,将itertools.imap替换为map

        import itertools
        
        def readwords(mfile):
            byte_stream = itertools.groupby(
              itertools.takewhile(lambda c: bool(c),
                  itertools.imap(mfile.read,
                      itertools.repeat(1))), str.isspace)
        
            return ("".join(group) for pred, group in byte_stream if not pred)
        

        示例用法:

        >>> import sys
        >>> for w in readwords(sys.stdin):
        ...     print (w)
        ... 
        I really love this new method of reading words in python
        I
        really
        love
        this
        new
        method
        of
        reading
        words
        in
        python
                   
        It's soo very Functional!
        It's
        soo
        very
        Functional!
        >>>
        

        我想在你的情况下,这将是使用该功能的方式:

        with open('words.txt', 'r') as f:
            for word in readwords(f):
                print(word)
        

        【讨论】:

          【解决方案6】:

          正常阅读该行,然后将其拆分为空格以将其分解为单词?

          类似:

          word_list = loaded_string.split()
          

          【讨论】:

            【解决方案7】:

            读完这行你可以做:

            l = len(pattern)
            i = 0
            while True:
                i = str.find(pattern, i)
                if i == -1:
                    break
                print str[i:i+l] # or do whatever
                i += l
            

            亚历克斯。

            【讨论】:

              【解决方案8】:

              Donald Miner 的建议看起来不错。简单而简短。我在前段时间编写的代码中使用了以下内容:

              l = []
              f = open("filename.txt", "rU")
              for line in f:
                  for word in line.split()
                      l.append(word)
              

              Donald Miner 建议的更长版本。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2015-10-14
                • 1970-01-01
                • 2011-02-15
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-10-06
                • 1970-01-01
                相关资源
                最近更新 更多