[英]How to remove specific word from a string in CSV(in Python)?
如果字符串以“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 中做到这一点?
使用正则表达式模块
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
会更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.