2017-12-29 4 views
-1

문자열이 'a'또는 'the'로 시작하는 경우 CSV 행을 다시 작성하고 싶습니다. 이를 위해 string.startswith()을 사용할 수 있습니다.CSV (파이썬에서)의 문자열에서 특정 단어를 제거하는 방법은 무엇입니까?

문제는 크게 다음과 같이 언급 될 수있다

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

가정하자 CSV는 다음과 같습니다 우리가이 작업을 수행하려면 어떻게

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

:

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

이 같아야합니다 파이썬? 성능을 필요로하는 경우

+0

예제는 * 쉼표로 구분 된 값 *과 같지 않습니다 (단락 기호는 반드시 쉼표 일 필요는 없지만). 그들은 pandas DataFrames의 문자열 표현과 비슷합니다. –

+0

이미 CSV 파일을 읽을 수있는 코드가 있습니까? 가지고 계신 경우 제공하십시오. –

답변

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가 빠릅니다.

+0

감사합니다. 'return' 대신'print'가 사용되면 작동합니다. –

관련 문제