2015-04-23 34 views
0

我是Python新手,这是我第一次使用它进行编码,因此请随身携带。我试图将一堆关键字保存在一个名为keywordtest.txt的文件中,其中包含文字如networkmanager,filemanagerspeaker等(每一行都在.txt文件中)。尝试将关键字从.txt文件保存到数组,并使用该数组搜索关键字

我已经将它保存到一个数组中,但是我希望它使用存储在该数组中的单词在另一个名为test的文档中搜索,并调出关键字被发现并存储的整行在另一个文档中称为results.txt。

我设法得到它在阵列中使用的词进行搜索,并将它们保存到另一个文件,但如果它不是在一条线上包含才会找到:

比如我搜索networkmanager和如果它只是networkmanager在它自己的文件中,我正在搜索的文件中会找到它,但是如果它像'我是网络管理者'那么它就不会选择它。

在此先感谢您的帮助。

#!\usr\bin\python 

x = [] 

with open("keywordtest.txt","r") as y: 
    for line in y: 
     x.append(line) 
print x 

theFile = open ("results.txt", "w") 
searchfile = open("test", "r") 

for line in searchfile: 
    for word in x: 
    if word in line: 
    theFile.write(line) 

theFile.close() 
searchfile.close() 

编辑:我张贴了我的一个版本,尝试一些代码时,我看到了使用“字”,而不是在一些地方“行”网上有人和尝试它,但它不喜欢它,下面的代码是我必须工作的代码,但只显示我正在寻找的单词,如果他们是自己的。

#!\usr\bin\python 

x = [] 

with open("keywordtest.txt","r") as y: 
    for line in y: 
     x.append(line) 
print x 


theFile = open ("results.txt", "w") 
searchfile = open("test", "r") 

for line in searchfile: 
    if line in x: theFile.write(line) 
    if line in x: print line 

theFile.close() 
searchfile.close() 
+0

最后你想要results.txt文件与匹配的单词??? –

回答

0
#!\usr\bin\python 

x = [] 

with open("keywordtest.txt","r") as y: 
    for line in y: 
     x.append(line) 
print x 

theFile = open ("results.txt", "w") 
searchfile = open("test.txt", "r") 

for line in searchfile: 
    for word in x: 
     if word in line.strip(): 
      theFile.write(word) 

theFile.close() 
searchfile.close() 
+0

抱歉,家伙对我发布的代码犯了一个错误,这是一个较旧的试用版和错误版本,无法正常工作。如果你可以看看我现在编写的代码,因为它在搜索一个单独的单词时运行,但如果这个单词在一行中,则不会找到它。对不起,并感谢您的帮助 – JamesB123

0

根据您的修改:

#!\usr\bin\python 
x = [] 

with open("keywordtest.txt","r") as y: 
    for line in y: 
     x.append(line) 
print x 


theFile = open ("results.txt", "w") 
searchfile = open("test.txt", "r") 

for line in searchfile: 
    for item in x: 
     if item in line: 
      theFile.write(line) 
      print line 

theFile.close() 
searchfile.close() 

这节省了匹配的单词在theFile.txt并打印出假设keywordtest.txt比赛每行有相同的只有一个字作为test.txt

+0

这已拉住我的测试文件中的所有内容,即使它没有包含在数组 – JamesB123

+0

@ JamesB123中的我的关键字之一,你能举出一个这些文件包含的例子吗? – bladexeon