替换python列表中的特定字符

时间:2016-12-20 11:10:12

标签: python string algorithm pandas

我有一个名为university_towns.txt的列表,其列表如下:

     ['Alabama[edit]\n',
        'Auburn (Auburn University)[1]\n',
        'Florence (University of North Alabama)\n',
        'Jacksonville (Jacksonville State University)[2]\n',
        'Livingston (University of West Alabama)[2]\n',
        'Montevallo (University of Montevallo)[2]\n',
        'Troy (Troy University)[2]\n',
        'Tuscaloosa (University of Alabama, Stillman College, Shelton State)[3]      [4]\n',
        'Tuskegee (Tuskegee University)[5]\n']

我想清理这个文本文件,使括号中的所有字符都替换为'' 。所以,我希望我的文本文件看起来像:

['Alabama',
 'Auburn',
 'Florence',
 'Jacksonville',
 'Livingston',
 'Montevallo',
 'Troy',
 'Tuscaloosa,
 'Tuskegee',
 'Alaska',
 'Fairbanks',
 'Arizonan',
 'Flagstaff',
 'Tempe',
 'Tucson']

我想按照以下方式执行此操作:

import pandas as pd
import numpy as np
file = open('university_towns.txt','r')
lines = files.readlines()
for i in range(0,len(file)):
    lines[i] = lines[i].replace('[edit]','')
    lines[i] = lines[i].replace(r' \(.*\)','')

有了这个,我可以删除'[edit]',但我无法删除'( )'中的字符串。

4 个答案:

答案 0 :(得分:1)

您可以将regex列表理解表达式一起使用:

import re

new_list = [re.match('\w+', i).group(0) for i in my_list]
#       match for word ^             ^ returns first word 

其中my_list是有问题的原始listnew_list保留的最终价值为:

['Alabama', 
 'Auburn', 
 'Florence', 
 'Jacksonville', 
 'Livingston', 
 'Montevallo', 
 'Troy', 
 'Tuscaloosa', 
 'Tuskegee']

答案 1 :(得分:0)

一个简单的正则表达式应该可以解决这个问题。

import re
output = [re.split(r'[[(]', s)[0].strip() for s in your_list]

答案 2 :(得分:0)

字符串上的replace方法替换实际的子字符串。你需要使用正则表达式:

import re
#...
line[i] = re.sub(r' (.*)', '', line[i])

答案 3 :(得分:0)

您可以使用re.sub代替replace

import re
# your code here
lines[i] = re.sub(r' \(.*\)','', lines[i])
相关问题