如果字段与另一个字段部分匹配,则删除CSV中的行

问题描述 投票:-3回答:1

如果字段与其他字段部分匹配,我想删除CSV文件中的行。

例如:

serial       book name                     author     

1.          Ramakrishna Kathamrita Vol1     Sri M     
2.          Ramakrishna Kathamrita Vol2     Sri M     
3.          Ramakrishna Kathamrita Vol3     Sri M     

我想这三个只有一个条目。它应该只返回:

serial       book name          author  

 1.          Ramakrishna Kathamrita Vol1     Sri M   

我们有什么方法可以用Python做到这一点?

编辑:(29-12-2017 17:05)

很抱歉不清楚。

我们可以设置以下标准。

  1. 如果书名具有n字样,则至少firstn-1字应匹配。
  2. 如果1.满意,它将在询问用户时删除该行。

这个想法非常明显:

my_string1 = "Ramakrishna Kathamrita Vol1"
my_string2 = "Ramakrishna Kathamrita Vol2"    

splitted1 = my_string1.split()
splitted2 = my_string2.split()

if(splitted1[0] = splitted2[0] & splitted1[1] = splitted2[1])
     then ask the user whether to delete the row;wait for 'y/n'

我们也可以得到字数:

def word_count(string):
    tokens = string.split()
    n_tokens = len(tokens)
    return n_tokens

现在我们如何实现它1)对于CSV 2)在询问时删除行?

python csv
1个回答
0
投票

如果某个字段与其他字段部分匹配。

您可以使用字符串距离算法。 StringDist模块可能很有用,但您需要定义什么是您的similarity标准。

© www.soinside.com 2019 - 2024. All rights reserved.