我是Python新手,为了简单的任务我一直在玩它。我有一堆需要以复杂方式操作的CSV,但为了学习Python,我将其分解为更小的任务。有没有让这种逻辑更优雅的Pythonic方法?
现在,给定一个字符串列表,我想删除字符串中任何名字的用户定义的标题前缀。任何包含名称的字符串将只包含名称,有或没有标题前缀。我有以下几点,它的工作原理,但它感觉不必要的复杂。是否有更多的Pythonic方法来做到这一点?谢谢!
# Return new list without title prefixes for strings in a list of strings.
def strip_titles(line, title_prefixes):
new_csv_line = []
for item in line:
for title_prefix in title_prefixes:
if item.startswith(title_prefix):
new_csv_line.append(item[len(title_prefix)+1:])
break
else:
if title_prefix == title_prefixes[len(title_prefixes)-1]:
new_csv_line.append(item)
else:
continue
return new_csv_line
if __name__ == "__main__":
test_csv_line = ['Mr. Richard Stallman', 'I like cake', 'Mrs. Margaret Thatcher', 'Jean-Claude Van Damme']
test_prefixes = ['Mr.', 'Ms.', 'Mrs.']
print strip_titles(test_csv_line, test_prefixes)
“Jane Doe女士”和“Betty Bloggs夫人”以及“Fred Nerk先生”,还有很多书呆子[缩写词,缩略词]和按键节俭的民谣和女士憎恶的民谣。 “和”希尔德加德希格斯小姐“? – 2010-09-24 02:12:21
@John谢天谢地,这不是一个问题,因为数据来自另一个来源,并为此提供了一致的方案。 – bsamek 2010-09-24 02:22:23
“一致的数据源”?我将在“Famous Last Words”下提交该文件:-) – 2010-09-24 03:13:31