0

所以我正在尝试制作一个读取文件并将每个单词存储到字符串列表中的程序。我可以将每一行添加到字符串列表中(参见下面的代码),但是如何将每个单词添加到字符串列表中?

此外,由于这是一个 Mad Libs 程序,我将有一些看起来像、名词身体部位的短语。我如何将正文部分作为一个字符串存储到列表中,因为它在技术上是两个单独的单词?

参考代码:

def main():
  file_list = []
  while True: #while loop that runs until the user puts in a file name...
    #or types in quit
    #asks the user for a file name, or gives them an option to quit
    file_name = raw_input("Enter in the name of the file, or type in quit to quit: ")
    if file_name == "quit":
            sys.exit(0) #quits the program
    else:
            try: #attempts to open the file
                fin = open(file_name)
                break
            except: #prints out if file name doesn't exist
                    print "No, no, file no here."
  for eachLine in fin: #strips out the new lines from the file
        file_list.append(eachLine.strip())
  print file_list
if __name__ == '__main__':
    main()
4

1 回答 1

2
file_list.extend(eachLine.split())
于 2013-04-12T20:48:53.027 回答