所以我正在尝试创建一个读取文件的程序,并将每个单词存储到字符串列表中。我可以将每一行添加到字符串列表中(请参阅下面的代码),但如何将每个单词添加到字符串列表中?
另外,由于这是一个Mad Libs程序,我会有一些看起来像 noun 或 body part 的短语。我如何将正文部分作为一个字符串存储到列表中,因为它在技术上是两个单独的单词?
参考代码:
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()
答案 0 :(得分:2)
file_list.extend(eachLine.split())