-链接到python文件 | -链接到csv testdata文件
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 = ['.', ',', ';', '\(', '\)', ':', '\.\.\.', '!']
现在,我在做什么错?
您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'\.'
您可能还想阅读“从Python中的字符串中删除标点符号的最佳方法”中的一些解决方案
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句