2017-10-20 31 views
0

我有许多行和许多列一个非常大的阵列(称为“self.csvFileArray”),其由,我已经从一个CSV文件中读取行,在与CSV文件涉及一类使用下面的代码...怎样才能有效地替代了大规模的基于CSV-字符串数组,使用字典?

with open(self.nounDef["Noun Source File Name"], 'rU') as csvFile: 
    for idx, row in enumerate(csv.reader(csvFile, delimiter=',')): 
    if idx == 0: 
     self.csvHeader = row 
    self.csvFileArray.append(row) 

我有一个很长字典,我想使用的替代品替代的映射......

replacements = {"str1a":"str1b", "str2a":"str2b", "str3a":"str3b", etc.} 

我想这样做是一个类的方法,看起来如下...

def m_globalSearchAndReplace(self, replacements): 
    # apply replacements dictionary to self.csvFileArray... 

我的问题:什么是整个阵列“self.csvFileArray”,使用“replacements”字典替换字符串的最有效方法是什么?

笔记澄清:

  1. 我看了看this post,但似乎无法得到它的这种情况下工作。

  2. 另外,我想更换匹配的,不只是整个单词中的字符串。因此,使用“SomeCompanyName”替换映射:“xyz”,我可能会有一个像“”的公司SomeCompanyName有一个名为abcSomeCompanyNamedef的产品专利“您会注意到该字符串必须被替换两次,在句子中......一次作为一个整体单词,一次作为嵌入的字符串。

+0

请问您可以添加阵列样本吗? – MattR

+0

'self.csvFileArray'的最终目的是什么?应该将所有行保存到一个新文件中? – RomanPerekhrest

+0

self.csvFileArray表示从原始CSV文件读入的所有行。我们正在构建一个“智能洗刷器”,通过在不丢失“密钥完整性”的情况下剥离机密数据来清理和转换数据,然后再将其写回到可发送的新CSV文件与供应商合作。 –

回答

1

与以上并已全面测试以下作品...

def m_globalSearchAndReplace(self, dataMap): 
    replacements = dataMap.m_getMappingDictionary() 
    keys = replacements.keys() 
    for row in self.csvFileArray: # Loop through each row/list 
     for idx, w in enumerate(row): # Loop through each word in the row/list 
     for key in keys: # For every key in the dictionary... 
      if key != 'NULL' and key != '-' and key != '.' and key != '': 
      w = w.replace(key, replacements[key]) 
     row[idx] = w 
  1. 总之,通过在csvFileArray每一行循环,让每一个字。

  2. 然后,该行中的每一个字,遍历字典的(所谓的“替代品”)键来访问和应用每一个映射。

  3. 然后(假设条件正确)用它的映射值(在字典中)替换该值。

注:虽然它的工作原理,我不相信,用之不尽的循环是解决问题的最有效的方式,我相信必须有一个更好的方法,使用正则表达式。所以,我会稍微留意一下,看看有没有人可以改进答案。

+0

正则表达式也需要搜索整个时间,所以性能不会很好。此外,匹配正则表达式模式比字符串比较慢... – errantlinguist

+0

我可能能够在一起得到一些东西,但不幸的是,它会比我目前需要更多的时间... – errantlinguist

0

在一个大循环?你可以只加载CSV文件作为字符串,所以你只需要通过你的列表,而不是一次对每一个项目的样子。虽然它不是非常有效的python字符串是不可改变的,但您仍然面临同样的问题。

根据这个答案Optimizing find and replace over large files in Python(重新提高效率),也许一行一行地工作会更好,所以如果实际上成为一个问题,你没有巨大的字符串。

编辑:因此,像这样......

# open original and new file. 
with open(old_file, 'r') as old_f, open(new_file, 'w') as new_f: 
    # loop through each line of the original file (old file) 
    for old_line in old_f: 
     new_line = old_line 
     # loop through your dictionary of replacements and make them. 
     for r in replacements: 
      new_line = new_line.replace(r, replacements[r]) 
     # write each line to the new file. 
     new_f.write(new_line) 

无论如何,我会忘记该文件是一个CSV文件,只是把它当作线条或字符的大集合。

相关问题