【问题标题】:How to return a list of words from a text file in python如何从python中的文本文件中返回单词列表
【发布时间】:2014-11-12 12:03:08
【问题描述】:

我想返回在文本文件中找到的所有单词。这是我到目前为止的代码。

def get_dictionary_word_list():
    f = open('dictionary.txt')
    for word in f.read().split():
        print(word)

它使用打印功能工作,但不是打印单词,而是我想返回文本文件中的所有单词。使用 return 它只显示 'aa' 而不是文件中的单词。我不确定为什么它不能与 return 一起使用?

【问题讨论】:

  • 你想从你的文件中选择所有 2 个单词吗?

标签: python file python-3.x


【解决方案1】:

如果你在循环中使用了 return,它会在第一次迭代时返回,你只得到第一个单词。

您想要的是单词的聚合 - 或者更好的是,返回从拆分单词中返回的数组。您可能需要清理换行符。

def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope
    with open('dictionary.txt') as f:
        # return the split results, which is all the words in the file.
        return f.read().split()

要取回字典,您可以使用它(注意换行符):

def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope

    with open('dictionary.txt') as f:
        # create a  dictionary object to return
        result = dict()
        for line in f.read().splitlines():
            # split the line to a key - value.
            k, v = line.split()
            # add the key - value to the dictionary object
            result[k]  = v
        return result

要取回键值项,您可以使用类似这样的方法返回generator(请记住,只要生成器保持打开状态,文件就会保持打开状态)。如果您想要的话,您可以修改它以仅返回单词,这非常简单:

def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope
    with open('dictionary.txt') as f:
        for line in f.read().splitlines():
            # yield a tuple (key, value)
            yield tuple(line.split())

第一个函数的示例输出:

xxxx:~$ cat dictionary.txt 
a asd
b bsd
c csd
xxxx:~$ cat ld.py 
#!/usr/bin/env python

def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope
    with open('dictionary.txt') as f:
        # return the split results, which is all the words in the file.
        return f.read().split()

print get_dictionary_word_list()
xxxx:~$ ./ld.py 
['a', 'asd', 'b', 'bsd', 'c', 'csd']

【讨论】:

  • 这不是他要的。
  • 那么他在问什么?似乎他使用 return 而不是 print 停止循环并单独返回第一个单词。
  • @reutsharabani 我只想要一个简单的函数来返回文件中存储的所有单词。我使用了您提到的第一个代码,但它没有返回任何空白的单词?我的代码有效,但不适用于返回函数
  • @sc14sd 它对我有用。如果文件中确实有某些东西,它必须返回 SOMETHING。我添加了示例输出。
  • @ReutSharabani 啊是的,它确实有效!谢谢你。那是因为文件里的字比较多,只是用的时间有点长。
【解决方案2】:

这个怎么样:

def get_dictionary_word_list(fname):
    with open(fname) as fh:
        return set(fh.read().split())

【讨论】:

    【解决方案3】:
    def get_dictionary_word_list():
        f = open('dictionary.txt')
        ll=[]
        for word in f.read().split():
            ll.append(word)
        return ll
    

    试一试列表

    【讨论】:

      【解决方案4】:

      试试这个:-

      def func():
          with open('new.txt') as f:
              return f.read() # returns complete file,
      
      with open('out.txt', 'w+') as w:
          w.write(func())
          w.seek(0)
          print w.read()
      

      Generators:-

      def func():
          with open('new.txt') as f:
              yield f.read()
      data = func()
      with open('out2.txt', 'w+') as w:
          for line in data:
              w.write(line) #or you may use  map(w.write, line)
              w.seek(0)
              print w.read()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-05
        • 2015-05-31
        • 1970-01-01
        相关资源
        最近更新 更多