【发布时间】:2017-12-29 03:45:48
【问题描述】:
如果某个字段与其他字段部分匹配,我想删除 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)
抱歉,不清楚。
我们可以设置以下标准。
- 如果书名包含
n字词,则至少第一个n-1字词应匹配。 - 如果满足
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)在询问时删除行?
【问题讨论】:
-
“部分匹配”的标准是什么?一旦您可以定义您可以对 CSV 行进行分组并根据需要使用字典(或
collections.defaultdict)或使用itertools.groupby()组合它们。 -
已编辑。希望问题现在很清楚。