2014-07-10 41 views
0

所以我有這個代碼在這裏搜索一個叫做「聲稱」的csv文件,看它是否包含在csv文件「sexualHarassment」中找到的任何單詞,並將這些結果打印到新的csv文件。這部分工作很好。輸出到csv沒有停止詞

我遇到麻煩的部分是刪除停用詞。我有第三個csv文件,其中包含一列停用詞。我無法弄清楚如何讓這些輸出沒有停用詞。謝謝。

這裏是我的代碼:

import csv 

    with open("claims.csv") as file1, open("sexualHarassment.csv") as file2, 
    open("stopwords.csv") as file3, open("output.csv", "wb+") as file4: 
     writer = csv.writer(file4) 
     key_words = [word.strip() for word in file2.readlines()] 
     stop_words = [stop.strip() for stop in file3.readlines()] 
     for row in file1: 
      row = row.strip() 
      for key in key_words: 
       if key in row: 
        writer.writerow([key, row]) 
+5

爲了回答您的標題的問題:是的,可以。不過,不知道它與帖子正文的關係。 – Kevin

+0

我頭腦裏有一個不同的問題,道歉 – Abtra16

+0

您是試圖從每一行中刪除停用詞,還是根本不打印行? – TheSoundDefense

回答

2

是的,你可以。

至於問題主體。

for key in keywords: 
    row = row.replace(key, "") 

編輯:

for key in stopwords: 
    row = row.replace(key, "") 

編輯結束

我不知道這是否是你的意圖,但除非你願意,你可以使用replace函數從該行刪除所有關鍵字可能會重複添加相同的行(如果每行存在多個關鍵字),您可能需要執行類似於

 for key in key_words: 
      if key in row: 
       writer.writerow([key, row]) 
       break # would not recommend using breaks but that's more personal taste 

 flag = False; 
     for key in key_words: 
      if key in row: 
       flag = True; 
     if flag: 
      writer.writerow([key, row]) 

LG

+0

謝謝,這實際上幫助我刪除了重複項(之後我會這樣做)。但是在參考答案的第一部分時,我並未嘗試刪除關鍵字,我試圖刪除停用詞 – Abtra16

+0

for @Daniel Kogan – Abtra16

+0

Sry,只是用停用詞替換關鍵字 –

1

如果你想從一個較長的字符串中刪除單詞的列表,你可以使用replace功能,像這樣:

row = "stop go stop stop2 yellow stop3 hi" 
stop_list = ["stop","stop2","stop3"]  # You'd get this from the file. 
for stop_word in stop_list: 
    row = row.replace(stop_word,"") 
print row         # Output: " go yellow hi" 

這基本上迭代在每一個停用詞上,並用""代替它,有效地將其刪除。

不要問我在哪裏提出的例子詞,因爲我不知道。