2015-04-23 33 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