【问题标题】:Replace items in a CSV file Python using a list使用列表替换 CSV 文件 Python 中的项目
【发布时间】:2015-03-09 14:50:59
【问题描述】:

我有一个如下列表:

['data-data analysis','word or words-phrase','rank-ranking']

和一个常规的 CSV 文件,它可以在其中任何位置(任何列)包含“-”之前的单词。我想用“-”后面的词替换那些。示例 CSV 文件可能如下所示:

h1,h2,h3
data of database,a,v
gg,word or words/word,gdg
asd,r,rank

我非常感谢任何帮助。

期望的输出:

h1,h2,h3
data analysis of database,a,v
gg,phrase/word,gdg
asd,r,ranking

【问题讨论】:

  • 这个问题看起来很接近stackoverflow.com/questions/19748676/…
  • @BobHaffner 是的,我试过了,但我的输出文件看起来很奇怪。它没有替换任何东西,而且整个表在同一个文件中重复了 29 次。
  • 你能包含所需的输出吗?
  • @Jasper 请找到已编辑的问题。

标签: python list csv dictionary replace


【解决方案1】:

这有一些技巧,所以在替换 data 时不会得到 data analysis of data analysisbase

输入.csv

h1,h2,h3
data of database,a,v
gg,word or words/word,gdg
asd,r,rank

Python 代码

#!python2
import csv
import re

# This builds a dictionary of key/value replacements.
# It wraps the key in word breaks to handle not replacing
# "database" when the key is "data".
L = ['data-data analysis','word or words-phrase','rank-ranking']
pairs = [w.split('-') for w in L]
replacements = {r'\b' + re.escape(k) + r'\b':v for k,v in pairs}

# Files should be opened in binary mode for use with csv module.
with open('input.csv','rb') as inp:
    with open('output.csv','wb') as outp:

        # wrap the file streams in csv reader and csv writer objects.
        r = csv.reader(inp)
        w = csv.writer(outp)

        for line in r:
            for i,item in enumerate(line):
                for k,v in replacements.items():
                    item = re.sub(k,v,item)
                line[i] = item
            w.writerow(line)

输出.csv

h1,h2,h3
data analysis of database,a,v
gg,phrase/word,gdg
asd,r,ranking

【讨论】:

  • 谢谢。这正是我想要的,但它说“ValueError:需要超过 1 个值来解包”指向替换 = {r'\b' + re.escape(k) + r'\b':v for k,v in对}
  • @amy,你用的是什么版本的 Python?此外,如果您的替换字符串之一中没有连字符,则可能会发生这种情况。您使用的是上面的确切代码吗?
  • 是的。我使用了确切的代码。另外,我使用的是 Python 2.7.6。所有替换字符串中都有一个连字符。
  • 上面的代码是 Python 3,所以在该行之后它会出现错误。您是否更改了列表L?我会做一个与 2.7 兼容的版本。
  • @amy 已针对 Python 2 更新。
猜你喜欢
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多