如何按指定规则为列表字符串中的姓名添加连字符?
解决方案:Python字符串处理实现需求
要实现这个按规则插入连字符的需求,我们可以用Python来处理,核心是先拆分字符串结构,再根据姓名部分的特征判断分割点,具体代码和解释如下:
original_list = [ 'Carter Copeland Melius Research LLC - Founding Partner, President and Research Analyst of Aerospace & Defense\n', 'Gregory D. Smith The Boeing Company - CFO and Executive VP of Enterprise Operations, Finance & Strategy\n', 'Maurita B. Sutedja The Boeing Company - VP of IR\n' ] processed_list = [] for item in original_list: # 先去除末尾换行符,再分割成「姓名+公司」和「职位」两部分 item_clean = item.rstrip('\n') name_company_part, position = item_clean.split(' - ', 1) # 把姓名+公司部分拆成单词列表 words = name_company_part.split() # 判断第二个单词是否包含点号,确定姓名的长度 if '.' in words[1]: # 第二个单词带点,姓名取前3个单词 name = ' '.join(words[:3]) company = ' '.join(words[3:]) else: # 第二个单词不带点,姓名取前2个单词 name = ' '.join(words[:2]) company = ' '.join(words[2:]) # 拼接成目标格式,再加上换行符 processed_item = f"{name} - {company} - {position}\n" processed_list.append(processed_item) # 输出结果 for line in processed_list: print(line, end='')
代码逻辑解释:
- 预处理字符串:先去掉每个字符串末尾的换行符,再用
' - '分割成「姓名+公司」和「职位」两部分,避免职位部分的空格干扰姓名和公司的拆分。 - 拆分单词判断规则:把「姓名+公司」拆成单词列表后,检查第二个单词是否包含
.:- 如果包含(比如
Gregory D. Smith中的D.),说明姓名是前3个单词,剩下的是公司名; - 如果不包含(比如
Carter Copeland),说明姓名是前2个单词,剩下的是公司名。
- 如果包含(比如
- 拼接目标格式:按照
姓名 - 公司 - 职位的格式拼接字符串,最后加上换行符还原原格式。
运行这段代码后,就能得到你想要的转换结果啦。
内容的提问来源于stack exchange,提问作者Alan003
相关产品推荐
相关产品推荐

