如何从CSV中删除字符串中的特定单词(在Python中)?

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

如果字符串以'a'或'the'开头,我想重写CSV行。我们可能会将string.startswith()用于此目的。

问题可能是这样严重说的:

if string.startswith('A' or 'The')
  remove 'a' and 'the'; keep the rest of the string; rewrite the row

假设CSV是:

ID    Book                Author
1.    A Study in Scarlet  Conan Doyle
2.    Aboltabol           Sukumar Roy
3.    The Bible           Matthew

它应该看起来像:

    ID    Book                Author
    1.    Study in Scarlet    Conan Doyle
    2.    Aboltabol           Sukumar Roy
    3.    Bible               Matthew

我们如何在Python中执行此操作?

python string csv
1个回答
1
投票

使用正则表达式模块

import re

pattern = re.compile("^(A|The)\s+(.+)", flags=re.IGNORECASE)

def process(word):
    w = pattern.match(word)
    return w.group(2) if w else word

process('A Study in Scarlet')  # 'Study in Scarlet'
process('Aboltabol')  # 'Aboltabol'
process('The Bible')  # 'Bible'

虽然如果你需要表现,startswith + split会更快。

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