简体   繁体   English

如何将从文件中读取的单词存储到列表中

[英]How to store words read from a file into a list

Apologies for the basic question but I am very new to this programming language. 对基本问题表示歉意,但我对这种编程语言并不熟悉。 I found similar questions but I cannot making them work for my specific case. 我发现了类似的问题,但我不能让它们适合我的具体案例。

My aim is to read words from a txt file (with more lines, each word is separated by a space), store them into a list and print the list to check what I am doing. 我的目标是从txt文件中读取单词(包含更多行,每个单词用空格分隔),将它们存储到列表中并打印列表以检查我在做什么。

The following code seems to work in terms of printing the single words, but apparently I am not storing them (or I am not able to access the list). 以下代码似乎在打印单个单词方面起作用,但显然我没有存储它们(或者我无法访问该列表)。

import os

def main():
    read_text(dir_path)

def read_text(file_name):
    file_data = []
    text_file = open(file_name,"r")

    for word in text_file.read().split():
        print(word)
        file_data.append(word)

    text_file.close()
    return file_data        

if __name__ == "__main__":
    main()

What am I doing wrong? 我究竟做错了什么? Thanks for any suggestions. 谢谢你的任何建议。

If you want to store the data list for further use, you need to retrieve the list that the read_text method returns: 如果要存储数据列表以供进一步使用,则需要检索read_text方法返回的列表:

def main():
    resultList = read_text(dir_path) # store the list
    # use it...
def read_text(file_name):
    file_data = []
    text_file = open(file_name,"r")

    for word in text_file.read().split():
        print(word)
        file_data.append(word)

    text_file.close()
    return file_data        


if __name__ == "__main__":
    the_list = read_text('example.txt')
    print the_list

This worked for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM