如何在字符串中搜索模式并将其替换为空格?

时间:2016-12-09 16:18:36

标签: python python-2.7 csv

- Link to the python-file | - Link to the csv testdata file

import csv 
import nltk
import re
from array import *
#Expressions
rgx_list = ['.', ',', ';', '\(', '\)', ':', '\.\.\.', '!']
#New empty array
ntitle = []
#Open a csv
with open('tripadvisor_dieburg.csv') as file:   
    reader = csv.DictReader(file)
    #Get the title and replace the expressions  
    for row in reader:
        for r in rgx_list:
            new_title = row['title']
            rgx = re.compile(r)
            new_title = re.sub(rgx, '', new_title)
        #Append to the array    
        ntitle.append(new_title)            
#Print the new title
for n in ntitle:
    print n 

我为正则表达式创建了一个名为rgx_list的数组,然后我打开了一个包含内容的csv文件。然后我尝试用空格替换标题row['title']中的正则表达式。 之后,我想将新标题复制到名为" ntitle"的新数组中。

只有'!' 将替换为字符串,但我希望所有正则表达式都将被替换。
rgx_list = ['.', ',', ';', '\(', '\)', ':', '\.\.\.', '!'] 现在,我做错了什么?

1 个答案:

答案 0 :(得分:0)

您每次都在循环中重置new_title

for row in reader:
    for r in rgx_list:
        new_title = row['title']  # here - discards what you replace
        rgx = re.compile(r)
        new_title = re.sub(rgx, '', new_title)

应该是

for row in reader:
    new_title = row['title']  # here - only assign once
    for r in rgx_list:
        rgx = re.compile(r)
        new_title = re.sub(rgx, '', new_title)

我认为'.'应为r'\.'

您可能还想阅读Best way to strip punctuation from a string in Python

中的一些解决方案
相关问题