2016-08-01 60 views
1

我想根據要刪除的文件在不同的.txt文件中基於要刪除的數據列表來混淆出現在.csv文件列中的單詞。從.txt文件以.csv混淆數據

理想情況下,我將能夠忽略我的數據的情況,然後在.csv文件中,用'*'替換「刪除」文件中的匹配詞。我不知道什麼是最好的方法將取代.csv文件中的單詞,同時也忽略大小寫。到目前爲止,我的工作並不奏效,我很樂於接受解決方案。

實施例的數據文件:

This is a line of text in .csv column that I want to remove a word from or data such as 123 from. 

我的.txt文件將是數據的列表,以除去:

want 
remove 
123 

輸出應爲:

This is a line of text in .csv column that I **** to ****** a word or data such as *** from. 

我的代碼:

import csv 

with open('MyFileName.csv' , 'rb') as csvfile, open ('DataToRemove.txt', 'r') as removetxtfile: 
    reader = csv.reader(csvfile) 
    reader.next() 
    for row in reader: 
     csv_words = row[3].split(" ") #Gets the word for the 4th column in .csv file 
      for line in removetxtfile: 
       for wordtoremove in line.split(): 
        if csv_words.lower() == wordtoremove.lower() 
         csv_words = csv_words.replace(wordtoremove.lower(), '*' * len(csv_words)) 
+1

我認爲你試圖將這些代碼壓縮成太多的循環以致效率低下。你使用'row [3] .split(「」)';這是否意味着您想混淆的_only_單詞/短語在該列的句子中?另外,實際產出是多少?這裏的一切都被讀入,但沒有別的。 – roganjosh

+0

是的,其餘的數據列沒有我想要混淆的單詞/短語。我在想,這麼多嵌套for循環不會很高效,但是,我是Python新手,不確定更好的方法。我的實際輸出應該從.txt文件中的文字(忽略大小寫)出現在.csv文件列中的任何位置,並使用'*'替換.csv列中的匹配詞。 – TechPadawan24

回答

0

我會從構建一組審查單詞開始。我的輸入基本上是換行符分隔的單詞的純文本文件。如果你的文本文件不同,你可能需要單獨解析。

其他的想法:

創建的,而不是試圖覆蓋輸入文件單獨審查文件輸出。這樣,如果你搞砸你的算法,你不會失去你的數據。

您在第4列上做了.split(" "),只有當該列中有多個單詞,空格分隔時纔有必要。如果不是這種情況,可以跳過for w in csv_words循環,循環遍歷第4列中的所有單詞。

import csv 
import re 
import string 

PUNCTUATION_SPLIT_REGEX = re.compile(r'[\s{}]+'.format(re.escape(string.punctuation))) 

# construct a set of words to censor 
censor_words = set() 
with open ('DataToRemove.txt', 'r') as removetxtfile: 
    for l in removetxtfile: 
    words = PUNCTUATION_SPLIT_REGEX.split(l) 
    for w in words: 
     censor_words.add(w.strip().lower()) 

with open('MyFileName.csv' , 'rb') as csvfile, open('CensoredFileName.csv', 'w') as f: 
    reader = csv.reader(csvfile) 
    # reader.next() 
    for row in reader: 
     csv_words = row[3].split(' ') #Gets the word for the 4th column in .csv file 
     new_column = [] 
     for w in csv_words: 
      if w.lower() in censor_words: 
       new_column.append('*'*len(w)) 
      else: 
       new_column.append(w) 
     row[3] = ' '.join(new_column) 
     f.write(' '.join(row) + '\n') 
+0

可能還想談論修剪/忽略標點符號嗎? – RoadieRich

+0

當然。通過標點符號添加了一些分割。那部分沒有通過btw測試ymmv – James

+0

James,這太接近了!在我的最後,我確實改變了最後一行以返回逗號分隔符。但是,我沒有考慮到第4列中的數據在某些行中包含逗號和新行。您指出創建一個新文件的好事。如何用逗號和換行符處理數據的最佳方法是什麼,但是仍然能夠通過逗號分隔的文件進行上傳? – TechPadawan24