您好我的大学任务要求我们创建一个
的python程序file1
file2
file3
,其中每个文件名用空格分隔。此输入分配给变量FList
。 FList
拆分为三个文件名file1
,file2
和file3
。 FList
中的每个文件,程序会读取文件中的字词,并将这些字符串存储到各自的列表中:wordList1
,wordList2
和wordList3
。例如,file1
中的字词将分配给wordList1
。 searchWord
。 wordList1
,wordList2
和wordList3
中搜索searchWord
,并计算每个文件中的匹配数,并将结果分配给各自的变量:{ {1}},file1Results
和file2Results
。 file3Results
我在我的桌面上创建了三个.txt文件,名为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
,output.txt
,output2.txt
但由于某种原因,当我测试运行该程序时,它说{{1} }不存在。
答案 0 :(得分:0)
我无法告诉您的输入是什么,但听起来您正在寻找错误目录中的文件。
f1 = open('output1.txt')
将搜索正在运行python脚本的文件夹中的输出。 您可能需要的是这样的事情:
desktop_path = 'C:/Users/YOURNAME/Desktop/'
f1 = open(desktop_path + 'output1.txt') # open(desktop_path + Flist[0])
此外,可能存在的问题是
Flist.split()
的工作原理如下:
例如,' 1 2 3' .split()返回[' 1',' 2',' 3']和' 1 2 3' .split(无,1)返回[' 1',' 2 3']。
您可以在此here找到更多信息。
答案 1 :(得分:0)
我建议你添加
Building
到脚本的开头并运行它;它会告诉你当前正在使用的目录。
如果我在桌面上保存脚本并通过双击运行它,它将以import os
print(os.getcwd())
作为当前目录运行。我怀疑你的情况是这样的,你恰好在该目录中有一个名为c:\windows\system32
的文件。
如果是这种情况,您可以使用output.txt
使其显示在正确的位置。