如何在Python中按句号拆分句子并给每句加双引号(DataFrame场景)
解决方法
你已经把patterns列转成字符串类型了,接下来可以用两种方式给每个以句号结尾的句子加上双引号:
方法一:正则表达式替换
直接用str.replace结合正则匹配每个独立句子,自动包裹双引号:
df['patterns'] = df['patterns'].str.replace(r'(?<=^|, )([^.]+[.])', r'"\1"', regex=True)
这个正则会精准匹配符合要求的句子(要么在字符串开头,要么跟在, 之后且以句号结尾),替换后直接得到目标格式。
方法二:拆分-处理-拼接
如果对正则不太熟悉,也可以用更直观的拆分拼接逻辑:
# 按", "分割成单个句子的列表,逐个加引号后再拼接 df['patterns'] = df['patterns'].str.split(', ').apply( lambda lst: ', '.join([f'"{sent}"' for sent in lst]) )
执行后就能得到你期望的结果:
| patterns |
|---|
| "Keep related supplies in the same area.", "Make an effort to clean a dedicated workspace after every session.", "Place loose supplies in large, clearly visible containers.", "Use clotheslines and clips to hang sketches, photos, and reference material.", "Use every inch of the room for storage, especially vertical space.", "Use chalkboard paint to make space for drafting ideas right on the walls.", "Purchase a label maker to make your organization strategy semi permanent.", "Make a habit of throwing out old, excess, or useless stuff each month." |
内容的提问来源于stack exchange,提问作者Naeemah Small
相关产品推荐
相关产品推荐

