我想根據要刪除的文件在不同的.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))
我認爲你試圖將這些代碼壓縮成太多的循環以致效率低下。你使用'row [3] .split(「」)';這是否意味着您想混淆的_only_單詞/短語在該列的句子中?另外,實際產出是多少?這裏的一切都被讀入,但沒有別的。 – roganjosh
是的,其餘的數據列沒有我想要混淆的單詞/短語。我在想,這麼多嵌套for循環不會很高效,但是,我是Python新手,不確定更好的方法。我的實際輸出應該從.txt文件中的文字(忽略大小寫)出現在.csv文件列中的任何位置,並使用'*'替換.csv列中的匹配詞。 – TechPadawan24