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

2024-04-20 06:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如果某个字段与其他字段部分匹配,我想删除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中有什么方法可以做到这一点吗?你知道吗

编辑: (2017年12月29日17:05)

抱歉说不清楚。你知道吗

我们可以设定以下标准。你知道吗

  1. 如果书名有n个单词,那么至少前n-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)对于CSV2)请求时删除行?你知道吗


Tags: namemyserial单词authorsplittokenssri