【发布时间】:2016-02-10 02:08:34
【问题描述】:
您好,我在大学作业中遇到问题,要求我们创建一个 python 程序
- 要求用户输入三个包含单词的文件名,格式为
file1file2file3,其中每个文件名由空格分隔。此输入分配给变量FList。 - 程序将
FList拆分为三个文件名file1、file2和file3。 - 对于
FList中的每个文件,程序从文件中读取单词并将这些字符串存储到它们各自的列表中:wordList1、wordList2和wordList3。例如,来自file1的单词将分配给wordList1。 - 程序要求用户输入搜索词并将其分配给
searchWord。 - 程序在
wordList1、wordList2和wordList3中搜索searchWord,并计算每个文件中的匹配数并将结果分配给它们各自的变量:file1Results、file2Results和@ 987654342@。
Flist=raw_input("Please enter the three filenames seperated by spaces")
Flist=Flist.split()
file1=open(Flist[0],"r")
wordList1=file1.read().split()
file1.close()
file2=open(Flist[1],"r")
wordList2=file2.read().split()
file2.close()
file3=open(Flist[2],"r")
wordList3=file3.read().split()
file3.close()
searchWord=raw_input("Which word would you like to search ")
file1Results=wordList1.count(searchWord)
file2Results=wordList2.count(searchWord)
file3Results=wordList3.count(searchWord)
print "file1Results=",file1Results
print "file2Results=",file2Results
print "file3Results=",file3Results
我在桌面上创建了三个 .txt 文件,分别命名为 output.txt、output2.txt、output3.txt,但由于某种原因,当我测试运行该程序时,它显示 output2.txt 不存在。
【问题讨论】:
-
我在您的代码中看不到任何会导致您提到的错误的内容。你确定你没有在文件名中打错字(在实际的文件系统中,或者当你将文件名提交给 Python 程序时)?你能显示异常的回溯吗?
-
应该是Flist=Flist.split(" ")吗?
-
您的程序在哪个目录中,相对于您的 .txt 文件,以及您如何在命令行中引用 .txt 文件?
-
...如果您输入
output.txt output.txt output.txt会发生什么?它抱怨那个文件吗? -
@White
.split()默认会在空白处分割。
标签: python python-2.7