如何在python中从文本文件返回单词列表

2024-04-25 07:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想返回在文本文件中找到的所有单词。这是我目前掌握的密码。

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

它使用print功能工作,但不打印我想返回文本文件中所有单词的单词。使用return只显示“aa”,而不显示文件中的单词。我不知道为什么它不能和return一起工作?


Tags: intxt密码forreadgetdictionaryreturn
3条回答

如果在循环中使用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']
def get_dictionary_word_list():
    f = open('dictionary.txt')
    ll=[]
    for word in f.read().split():
        ll.append(word)
    return ll

尝试查看列表

这个怎么样:

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

相关问题 更多 >