更改csv python中相似单词的所有出现

时间:2016-03-18 04:57:10

标签: python-2.7 csv

我想替换一个特定字词,' my'与你的'。但似乎我的代码只能改变一种外观。

import csv
path1 = "/home/bankdata/levelout.csv"
path2 = "/home/bankdata/leveloutmodify.csv"
in_file = open(path1,"rb")
reader = csv.reader(in_file)
out_file = open(path2,"wb")
writer = csv.writer(out_file)

with open(path1, 'r') as csv_file:
    csvreader = csv.reader(csv_file)
    col_count = 0
    for row in csvreader:
        while row[col_count] == 'my':
            print 'my is used'
            row[col_count] = 'your'
            #writer.writerow(row[col_count])               
        writer.writerow(row)               
        col_count +=1

让我们说句子是

'my book is gone and my bag is missing'

输出

your book is gone and my bag is missing

第二件事是我想让它看起来没有逗号分隔:

print row

输出

your,book,is,gone,and,my,bag,is,missing,

1 个答案:

答案 0 :(得分:0)

对于第二个问题,我仍然试图找到正确的一个,因为它一直以逗号分隔给我相同的输出。

with open(path1) as infile, open(path2, "w") as outfile:
    for row in infile:
        outfile.write(row.replace(",", ""))
print row

它给了我结果:

your,book,is,gone,and,my,bag,is,missing

我把这句话发给我的Nao机器人,机器人似乎发出笨拙的声音,因为每个单词之间都有逗号。

我解决了它:

with open(path1) as infile, open(path2, "w") as outfile:
    for row in infile:
       outfile.write(row.replace(",", ""))
with open(path2) as out:
    for row in out:
       print row

它给了我我想要的东西:

your book is gone and your bag is missing too

然而,还有更好的方法吗?